@serfab/cadre-core 1.23.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.
- package/README.md +216 -294
- package/dist/arachnode-stub.d.ts +12 -4
- package/dist/arachnode-stub.js +15 -8
- package/dist/arachnode-stub.js.map +1 -1
- package/dist/cadre-invite-protocol.js +5 -4
- package/dist/cadre-invite-protocol.js.map +1 -1
- package/dist/cadre-node.d.ts +145 -44
- package/dist/cadre-node.js +239 -79
- package/dist/cadre-node.js.map +1 -1
- package/dist/control-authorization.d.ts +14 -2
- package/dist/control-authorization.js +8 -3
- package/dist/control-authorization.js.map +1 -1
- package/dist/control-cohort.d.ts +27 -13
- package/dist/control-cohort.js +21 -14
- package/dist/control-cohort.js.map +1 -1
- package/dist/control-database.d.ts +18 -16
- package/dist/control-database.js +57 -22
- package/dist/control-database.js.map +1 -1
- package/dist/control-protocol-guard.d.ts +1 -1
- package/dist/control-protocol-guard.js +7 -3
- package/dist/control-protocol-guard.js.map +1 -1
- package/dist/control-read-retry.d.ts +49 -11
- package/dist/control-read-retry.js +56 -15
- package/dist/control-read-retry.js.map +1 -1
- package/dist/control-retry.d.ts +32 -3
- package/dist/control-retry.js +35 -4
- package/dist/control-retry.js.map +1 -1
- package/dist/control-schema-version.d.ts +5 -5
- package/dist/control-schema-version.js +5 -5
- package/dist/control-schema-version.js.map +1 -1
- package/dist/control-schema.d.ts +5 -5
- package/dist/control-schema.js +1032 -1011
- package/dist/control-schema.js.map +1 -1
- package/dist/control-write-retry.d.ts +54 -65
- package/dist/control-write-retry.js +134 -158
- package/dist/control-write-retry.js.map +1 -1
- package/dist/delegate-admission.d.ts +1 -1
- package/dist/delegate-admission.js +1 -1
- package/dist/edge-node/config.d.ts +4 -3
- package/dist/edge-node/config.js +11 -9
- package/dist/edge-node/config.js.map +1 -1
- package/dist/edge-node/dissolve.d.ts +4 -4
- package/dist/edge-node/dissolve.js +4 -4
- package/dist/edge-node/edge-join.d.ts +1 -1
- package/dist/edge-node/edge-join.js +1 -1
- package/dist/edge-node/edge-node.js +2 -2
- package/dist/edge-node/edge-node.js.map +1 -1
- package/dist/edge-node/index.d.ts +1 -0
- package/dist/edge-node/index.js +1 -0
- package/dist/edge-node/index.js.map +1 -1
- package/dist/edge-node/join-credential.d.ts +1 -1
- package/dist/edge-node/join-credential.js +1 -1
- package/dist/edge-node/lazy-raw-storage.js +12 -0
- package/dist/edge-node/lazy-raw-storage.js.map +1 -1
- package/dist/edge-node/listen-addrs.d.ts +21 -0
- package/dist/edge-node/listen-addrs.js +25 -0
- package/dist/edge-node/listen-addrs.js.map +1 -0
- package/dist/edge-node/owner-grant.d.ts +1 -1
- package/dist/edge-node/owner-grant.js +1 -1
- package/dist/edge-node/platform.d.ts +5 -4
- package/dist/edge-node/platform.js.map +1 -1
- package/dist/edge-node/strand-move.d.ts +1 -1
- package/dist/edge-node/strand-move.js +1 -1
- package/dist/edge-node/strands.js +27 -11
- package/dist/edge-node/strands.js.map +1 -1
- package/dist/index.d.ts +7 -5
- package/dist/index.js +18 -7
- package/dist/index.js.map +1 -1
- package/dist/invitation-bootstrap.d.ts +28 -5
- package/dist/invitation-bootstrap.js +41 -8
- package/dist/invitation-bootstrap.js.map +1 -1
- package/dist/link-budget.d.ts +53 -4
- package/dist/link-budget.js +58 -5
- package/dist/link-budget.js.map +1 -1
- package/dist/machine-removal.d.ts +2 -2
- package/dist/machine-removal.js +4 -3
- package/dist/machine-removal.js.map +1 -1
- package/dist/membership-connection-gater.d.ts +2 -2
- package/dist/membership-connection-gater.js +2 -2
- package/dist/membership-view.d.ts +2 -2
- package/dist/membership-view.js +2 -2
- package/dist/node-claim-payload.d.ts +15 -7
- package/dist/node-claim-payload.js +25 -9
- package/dist/node-claim-payload.js.map +1 -1
- package/dist/node-class.d.ts +36 -0
- package/dist/node-class.js +26 -0
- package/dist/node-class.js.map +1 -0
- package/dist/node-default-transports.d.ts +50 -3
- package/dist/node-default-transports.js +48 -3
- package/dist/node-default-transports.js.map +1 -1
- package/dist/node-roles.d.ts +118 -0
- package/dist/node-roles.js +142 -0
- package/dist/node-roles.js.map +1 -0
- package/dist/node-transports.d.ts +6 -2
- package/dist/node-transports.js +39 -7
- package/dist/node-transports.js.map +1 -1
- package/dist/owner-anchor-sync.js +1 -1
- package/dist/owner-key-export.js +1 -1
- package/dist/owner-key-flows.d.ts +1 -1
- package/dist/owner-key-store.js +1 -1
- package/dist/owner-signer.js +1 -1
- package/dist/peer-authorization.d.ts +3 -1
- package/dist/peer-authorization.js +3 -1
- package/dist/peer-authorization.js.map +1 -1
- package/dist/peer-dial.d.ts +74 -10
- package/dist/peer-dial.js +89 -17
- package/dist/peer-dial.js.map +1 -1
- package/dist/peer-join-backfill.js +4 -4
- package/dist/peer-join-backfill.js.map +1 -1
- package/dist/peer-record.d.ts +34 -9
- package/dist/peer-record.js +66 -13
- package/dist/peer-record.js.map +1 -1
- package/dist/pending-join-runner.d.ts +1 -1
- package/dist/pending-join-runner.js +1 -1
- package/dist/provider/client.d.ts +6 -5
- package/dist/provider/client.js +3 -3
- package/dist/provider/client.js.map +1 -1
- package/dist/provider/descriptor.d.ts +1 -1
- package/dist/provider/descriptor.js +1 -1
- package/dist/provider/oauth.d.ts +1 -1
- package/dist/provider/oauth.js +1 -1
- package/dist/provider/rent-node.d.ts +4 -3
- package/dist/provider/rent-node.js +3 -3
- package/dist/provider/rent-node.js.map +1 -1
- package/dist/relay-addrs.d.ts +62 -7
- package/dist/relay-addrs.js +74 -11
- package/dist/relay-addrs.js.map +1 -1
- package/dist/relay-reservation.d.ts +1 -1
- package/dist/relay-reservation.js +1 -1
- package/dist/relay-server.d.ts +6 -5
- package/dist/relay-server.js +5 -5
- package/dist/relay-server.js.map +1 -1
- package/dist/schema-verification.d.ts +13 -10
- package/dist/schema-verification.js +32 -24
- package/dist/schema-verification.js.map +1 -1
- package/dist/sealed-party-key.js +1 -1
- package/dist/seed-bootstrap.d.ts +4 -3
- package/dist/seed-bootstrap.js +6 -7
- package/dist/seed-bootstrap.js.map +1 -1
- package/dist/strand-addr-protocol.d.ts +8 -6
- package/dist/strand-addr-protocol.js +12 -10
- package/dist/strand-addr-protocol.js.map +1 -1
- package/dist/strand-app-schema-report.d.ts +16 -2
- package/dist/strand-app-schema-report.js +15 -0
- package/dist/strand-app-schema-report.js.map +1 -1
- package/dist/strand-cohort.d.ts +1 -4
- package/dist/strand-cohort.js.map +1 -1
- package/dist/strand-commit-durability.d.ts +1 -1
- package/dist/strand-database.d.ts +13 -6
- package/dist/strand-database.js +17 -9
- package/dist/strand-database.js.map +1 -1
- package/dist/strand-first-sync-gate.d.ts +3 -2
- package/dist/strand-first-sync-gate.js +3 -2
- package/dist/strand-first-sync-gate.js.map +1 -1
- package/dist/strand-formation-deadlines.d.ts +2 -2
- package/dist/strand-formation-deadlines.js +2 -2
- package/dist/strand-formation-protocol.d.ts +1 -1
- package/dist/strand-formation-protocol.js +51 -16
- package/dist/strand-formation-protocol.js.map +1 -1
- package/dist/strand-instance-manager.d.ts +67 -33
- package/dist/strand-instance-manager.js +164 -55
- package/dist/strand-instance-manager.js.map +1 -1
- package/dist/strand-membership-reconciler.d.ts +8 -3
- package/dist/strand-membership-reconciler.js +8 -3
- package/dist/strand-membership-reconciler.js.map +1 -1
- package/dist/strand-membership-writer.d.ts +2 -2
- package/dist/strand-membership-writer.js +41 -39
- package/dist/strand-membership-writer.js.map +1 -1
- package/dist/strand-move.js +1 -1
- package/dist/strand-network-config.d.ts +15 -5
- package/dist/strand-network-config.js +7 -6
- package/dist/strand-network-config.js.map +1 -1
- package/dist/strand-party-key-rotation.d.ts +7 -3
- package/dist/strand-party-key-rotation.js +7 -3
- package/dist/strand-party-key-rotation.js.map +1 -1
- package/dist/strand-party-machines.d.ts +19 -8
- package/dist/strand-party-machines.js +26 -11
- package/dist/strand-party-machines.js.map +1 -1
- package/dist/strand-party-peers.d.ts +36 -14
- package/dist/strand-party-peers.js +24 -15
- package/dist/strand-party-peers.js.map +1 -1
- package/dist/strand-peer-redial.d.ts +1 -1
- package/dist/strand-peer-redial.js +1 -1
- package/dist/strand-reactivity.d.ts +20 -17
- package/dist/strand-reactivity.js +31 -18
- package/dist/strand-reactivity.js.map +1 -1
- package/dist/strand-revocation-enforcer.d.ts +3 -3
- package/dist/strand-revocation-enforcer.js +3 -3
- package/dist/strand-wake-protocol.d.ts +19 -7
- package/dist/strand-wake-protocol.js +22 -10
- package/dist/strand-wake-protocol.js.map +1 -1
- package/dist/strand-watcher.d.ts +1 -1
- package/dist/strand-watcher.js +1 -1
- package/dist/table-change-watch.js +1 -1
- package/dist/types.d.ts +116 -55
- package/dist/types.js.map +1 -1
- package/dist/webrtc-upgrade.d.ts +254 -0
- package/dist/webrtc-upgrade.js +355 -0
- package/dist/webrtc-upgrade.js.map +1 -0
- package/package.json +9 -9
- package/src/announce-addrs.ts +93 -93
- package/src/arachnode-stub.ts +18 -10
- package/src/bootstrap-peer-store-file.ts +44 -44
- package/src/bootstrap-peer-store.ts +214 -214
- package/src/cadre-invite-protocol.ts +741 -740
- package/src/cadre-node.ts +12462 -12280
- package/src/claim-proof.ts +147 -147
- package/src/control-authorization.ts +290 -276
- package/src/control-cohort.ts +223 -204
- package/src/control-database.ts +72 -28
- package/src/control-formation-recorder.ts +359 -359
- package/src/control-protocol-guard.ts +370 -366
- package/src/control-read-retry.ts +222 -180
- package/src/control-retry.ts +36 -4
- package/src/control-schema-version.ts +301 -301
- package/src/control-schema.ts +1108 -1087
- package/src/control-write-retry.ts +639 -669
- package/src/delegate-admission.ts +351 -351
- package/src/describe-thrown.ts +60 -60
- package/src/ed25519-key.ts +185 -185
- package/src/edge-node/config.ts +13 -10
- package/src/edge-node/dissolve.ts +252 -252
- package/src/edge-node/edge-join.ts +320 -320
- package/src/edge-node/edge-node.ts +1095 -1095
- package/src/edge-node/index.ts +60 -59
- package/src/edge-node/join-credential.ts +16 -16
- package/src/edge-node/lazy-raw-storage.ts +194 -178
- package/src/edge-node/listen-addrs.ts +26 -0
- package/src/edge-node/node-local.ts +84 -84
- package/src/edge-node/options.ts +195 -195
- package/src/edge-node/owner-grant.ts +63 -63
- package/src/edge-node/platform.ts +5 -4
- package/src/edge-node/strand-move.ts +266 -266
- package/src/edge-node/strands.ts +27 -12
- package/src/enrolled-machine-store-file.ts +43 -43
- package/src/enrolled-machine-store.ts +280 -280
- package/src/fetch-impl.ts +23 -23
- package/src/file-durable-slot.ts +64 -64
- package/src/file-safe-name.ts +32 -32
- package/src/formation-approval.ts +604 -604
- package/src/formation-token.ts +63 -63
- package/src/fs-atomic.ts +92 -92
- package/src/index.ts +987 -957
- package/src/invitation-bootstrap.ts +152 -118
- package/src/joined-strand-store.ts +553 -553
- package/src/key-store-file.ts +142 -142
- package/src/link-budget.ts +61 -5
- package/src/machine-removal.ts +211 -210
- package/src/member-redemption.ts +643 -643
- package/src/membership-connection-gater.ts +650 -650
- package/src/membership-view.ts +147 -147
- package/src/node-claim-payload.ts +34 -12
- package/src/node-class.ts +47 -0
- package/src/node-default-transports.ts +65 -3
- package/src/node-roles.ts +220 -0
- package/src/node-transports.ts +86 -49
- package/src/owner-anchor-sync.ts +172 -172
- package/src/owner-grant-protocol.ts +547 -547
- package/src/owner-key-export.ts +348 -348
- package/src/owner-key-flows.ts +109 -109
- package/src/owner-key-store.ts +1 -1
- package/src/owner-keys.ts +179 -179
- package/src/owner-signer.ts +92 -92
- package/src/peer-addr-book.ts +252 -252
- package/src/peer-authorization.ts +584 -582
- package/src/peer-dial.ts +698 -605
- package/src/peer-join-backfill.ts +961 -961
- package/src/peer-record.ts +71 -16
- package/src/pending-join-runner.ts +798 -798
- package/src/primary-lan-address.ts +47 -47
- package/src/provider/client.ts +327 -326
- package/src/provider/descriptor.ts +129 -129
- package/src/provider/index.ts +59 -59
- package/src/provider/oauth.ts +285 -285
- package/src/provider/rent-node.ts +276 -275
- package/src/relay-addrs.ts +90 -12
- package/src/relay-reservation.ts +1 -1
- package/src/relay-server.ts +99 -98
- package/src/schema-verification.ts +38 -23
- package/src/sealed-party-key.ts +190 -190
- package/src/seed-bootstrap.ts +8 -11
- package/src/seed-trust-policy.ts +353 -353
- package/src/self-address-update.ts +19 -19
- package/src/strand-addr-protocol.ts +17 -14
- package/src/strand-app-schema-report.ts +147 -122
- package/src/strand-cohort.ts +1 -5
- package/src/strand-commit-durability.ts +165 -165
- package/src/strand-database.ts +522 -510
- package/src/strand-first-sync-gate.ts +3 -2
- package/src/strand-formation-deadlines.ts +227 -227
- package/src/strand-formation-manager.ts +731 -731
- package/src/strand-formation-protocol.ts +1174 -1138
- package/src/strand-fret-addrs.ts +179 -179
- package/src/strand-instance-manager.ts +188 -63
- package/src/strand-membership-reconciler.ts +1315 -1310
- package/src/strand-membership-writer.ts +2152 -2150
- package/src/strand-move.ts +1 -1
- package/src/strand-network-config.ts +16 -6
- package/src/strand-offline.ts +178 -178
- package/src/strand-party-key-rotation.ts +440 -436
- package/src/strand-party-machines.ts +308 -293
- package/src/strand-party-peers.ts +151 -129
- package/src/strand-peer-redial.ts +1 -1
- package/src/strand-reactivity.ts +36 -19
- package/src/strand-revocation-enforcer.ts +758 -758
- package/src/strand-wake-protocol.ts +406 -394
- package/src/strand-watcher.ts +1 -1
- package/src/table-change-watch.ts +285 -285
- package/src/timed-step.ts +28 -28
- package/src/timeout-scheduler.ts +29 -29
- package/src/trusted-owner-store.ts +242 -242
- package/src/types.ts +3182 -3121
- 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
|
-
*
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
* (`
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
* a
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
*
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
*
|
|
120
|
-
*
|
|
121
|
-
*
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
*
|
|
127
|
-
*
|
|
128
|
-
*
|
|
129
|
-
*/
|
|
130
|
-
export
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
*
|
|
136
|
-
*
|
|
137
|
-
*
|
|
138
|
-
*
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
*
|
|
155
|
-
*
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
*
|
|
206
|
-
*
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
*
|
|
217
|
-
*
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
*/
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
*
|
|
287
|
-
*
|
|
288
|
-
*
|
|
289
|
-
*
|
|
290
|
-
*
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
return
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
*
|
|
401
|
-
*
|
|
402
|
-
*
|
|
403
|
-
*
|
|
404
|
-
*
|
|
405
|
-
*
|
|
406
|
-
*
|
|
407
|
-
*
|
|
408
|
-
*
|
|
409
|
-
*
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
*
|
|
475
|
-
*
|
|
476
|
-
*
|
|
477
|
-
*
|
|
478
|
-
* address
|
|
479
|
-
*
|
|
480
|
-
*
|
|
481
|
-
*
|
|
482
|
-
*
|
|
483
|
-
*
|
|
484
|
-
*
|
|
485
|
-
*
|
|
486
|
-
*
|
|
487
|
-
*
|
|
488
|
-
*
|
|
489
|
-
*
|
|
490
|
-
*
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
*
|
|
555
|
-
*
|
|
556
|
-
*
|
|
557
|
-
* the
|
|
558
|
-
*
|
|
559
|
-
* after
|
|
560
|
-
*
|
|
561
|
-
*
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
}
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
}
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
*
|
|
600
|
-
*
|
|
601
|
-
*
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
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
|
+
}
|