Repository navigation
Expand file tree
/
Copy pathbuilders.nim
More file actions
797 lines (695 loc) · 25.9 KB
/
Copy pathbuilders.nim
File metadata and controls
797 lines (695 loc) · 25.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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
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
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
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
558
559
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
# SPDX-License-Identifier: Apache-2.0 OR MIT
# Copyright (c) Status Research & Development GmbH
## This module contains a Switch Building helper.
{.push raises: [].}
import tables, chronos, chronicles, sequtils, lsquic
import
switch,
peerid,
peerinfo,
peeraddrpolicy,
stream/connection,
multiaddress,
crypto/crypto,
transports/[transport, tcptransport, wstransport, quictransport, memorytransport],
muxers/[muxer, mplex/mplex, yamux/yamux],
protocols/
[identify, secure/secure, secure/noise, secure/noisehfs, rendezvous, kademlia],
protocols/connectivity/[
autonat/server,
autonatv2/server,
autonatv2/service,
relay/relay,
relay/client,
relay/rtransport,
],
services/[identify_pusher, natservice, wildcardresolverservice, mdns],
connmanager,
upgrademngrs/muxedupgrade,
address_manager,
autotls/service,
nameresolving/[nameresolver, dnsresolver, system_resolver],
errors,
utils/[opt, tlsredact]
export
switch, peerid, peerinfo, peeraddrpolicy, connection, multiaddress, crypto, errors,
tlsredact, TLSPrivateKey, TLSCertificate, TLSFlags, ServerFlags,
connmanager.ConnectionLimits, connmanager.maxTotal, connmanager.maxInOut,
natservice.NATConfig, natservice.PortMappingMode, natservice.AutonatVersion,
natservice.PortMapperFactory, natservice.NATService, natservice.natConfig,
natservice.upnpConfig, natservice.natPmpConfig, natservice.explicitIpConfig,
natservice.autonatConfig, natservice.holePunchingConfig,
natservice.AutonatV2ServiceConfig, natservice.AutonatV2Service, natservice.natService,
mdns.MdnsPeer, mdns.MdnsPeerFound, mdns.MdnsService, mdns.MdnsMinQueryInterval,
mdns.MdnsMaxQueryInterval, mdns.MdnsDefaultQueryInterval,
mdns.MdnsDefaultMaxPendingCallbacks
logScope:
topics = "libp2p builders"
const MemoryAutoAddress* = memorytransport.MemoryAutoAddress
type
TransportBuilder* = proc(config: TransportConfig): Transport {.gcsafe, raises: [].}
TransportConfig* = ref object
upgr*: Upgrade
privateKey*: PrivateKey
autotls*: Opt[AutotlsService]
connManager*: ConnManager
rng*: Rng
RelayReservationHandler* = proc(addresses: seq[MultiAddress]) {.gcsafe, raises: [].}
SecureProtocol* {.pure.} = enum
Noise
NoiseHFS
## Post-quantum hybrid Noise (`Noise_XXhfs_25519+MLKEM768_ChaChaPoly_SHA256`).
## Mount alongside `Noise` (the default) so hybrid-capable peers
## negotiate the quantum-resistant handshake while classical-only
## peers still fall back to `/noise` transparently. When both are
## mounted NoiseHFS is always proposed first, whatever the order of
## the builder calls. The fallback is negotiated in the clear before
## any handshake, so an active attacker can force `/noise`; mount
## NoiseHFS alone when a classical session is not acceptable. This
## does not reach QUIC, which is secured by its own TLS handshake and
## ignores the mounted secure protocols.
KadMode* {.pure.} = enum
Client ## never serves queries; only issues them
Server ## always serves queries
Auto ## serves queries while autonat reports the node reachable
KadInfo = object
config*: KadDHTConfig
bootstrapNodes*: seq[(PeerId, seq[MultiAddress])]
mode*: KadMode
autoMode*: AutoModeConfig ## The windows of ``KadMode.Auto``.
NameResolverService = ref object of Service
resolver: NameResolver
NameResolverKind {.pure.} = enum
Custom
Dns
System
SwitchBuilder* = ref object
privKey: Opt[PrivateKey]
addresses: seq[MultiAddress]
announcedAddrs: seq[MultiAddress]
secureManagers: seq[SecureProtocol]
muxers: seq[MuxerProvider]
transports: seq[TransportBuilder]
rng: Rng
maxConnsPerPeer: int
limits: Opt[ConnectionLimits]
watermark: Opt[WatermarkPolicy]
scoring: PeerScoring
sendSignedPeerRecord: bool
protoVersion: string
agentVersion: string
nameResolver: NameResolver
nameResolverKind: NameResolverKind
nameServers: seq[TransportAddress]
dialRanking: bool
dialBackoff: Opt[DialBackoffConfig]
peerStoreCapacity: Opt[int]
addressTtls: AddressConfidenceTtls
autonatEnabled: bool
autonatV2ServerConfig: Opt[AutonatV2Config]
natConfig: Opt[NATConfig]
natPortMapperFactory: PortMapperFactory
autotlsConfig: Opt[AutotlsConfig]
circuitRelay: Opt[Relay]
resolvedRelay: Opt[Relay]
rdvConfig: Opt[RendezVousConfig]
kad: Opt[KadInfo]
identifyPusherEnabled: bool
mdnsEnabled: bool
mdnsCallback: MdnsPeerFound
mdnsQueryInterval: Duration
mdnsMaxPendingCallbacks: int
addressManagerConfig: Opt[AddressManagerConfig]
enableWildcardResolver: bool
addressPolicy: PeerAddressPolicy
allowUndialableAddrs: bool
method start(
self: NameResolverService, switch: Switch
) {.async: (raises: [CancelledError, LPError]).} =
self.resolver.start()
method stop(
self: NameResolverService, switch: Switch
) {.async: (raises: [CancelledError]).} =
await self.resolver.stop()
proc new*(T: type[SwitchBuilder]): T =
## Creates a SwitchBuilder
SwitchBuilder(
privKey: Opt.none(PrivateKey),
addresses: @[],
secureManagers: @[],
maxConnsPerPeer: -1,
limits: Opt.none(ConnectionLimits),
watermark: Opt.none(WatermarkPolicy),
scoring: PeerScoring(),
protoVersion: ProtoVersion,
agentVersion: AgentVersion,
autonatV2ServerConfig: Opt.none(AutonatV2Config),
natConfig: Opt.none(NATConfig),
autotlsConfig: Opt.none(AutotlsConfig),
circuitRelay: Opt.none(Relay),
rdvConfig: Opt.none(RendezVousConfig),
kad: Opt.none(KadInfo),
identifyPusherEnabled: false,
mdnsEnabled: false,
enableWildcardResolver: true,
addressPolicy: defaultAddressPolicy,
allowUndialableAddrs: false,
addressTtls: AddressConfidenceTtls(),
addressManagerConfig: Opt.none(AddressManagerConfig),
)
proc withPrivateKey*(
b: SwitchBuilder, privateKey: PrivateKey | Opt[PrivateKey]
): SwitchBuilder =
## Set the private key of the switch. Will be used to generate a PeerId
b.privKey = toOpt(privateKey)
b
proc withWildcardResolver*(b: SwitchBuilder, enabled: bool = true): SwitchBuilder =
b.enableWildcardResolver = enabled
b
proc withMdns*(
b: SwitchBuilder,
enabled: bool = true,
onPeerFound: MdnsPeerFound = nil,
queryInterval: Duration = MdnsDefaultQueryInterval,
maxPendingCallbacks: int = MdnsDefaultMaxPendingCallbacks,
): SwitchBuilder =
## Enable mDNS and optionally handle discovered peers.
if enabled:
doAssert queryInterval >= MdnsMinQueryInterval and
queryInterval <= MdnsMaxQueryInterval, "mDNS query interval is out of range"
doAssert maxPendingCallbacks >= 0, "mDNS callback limit cannot be negative"
## Each call replaces the full mDNS configuration: passing no `onPeerFound`
## clears a callback registered by an earlier `withMdns` call.
b.mdnsEnabled = enabled
b.mdnsCallback = onPeerFound
b.mdnsQueryInterval = queryInterval
b.mdnsMaxPendingCallbacks = maxPendingCallbacks
b
proc withAddresses*(b: SwitchBuilder, addresses: seq[MultiAddress]): SwitchBuilder =
## Set the listening addresses of the switch
b.addresses = addresses
b
proc withAddress*(b: SwitchBuilder, address: MultiAddress): SwitchBuilder =
## Set the listening address of the switch
b.withAddresses(@[address])
proc withAddresses*(
b: SwitchBuilder, addresses: seq[MultiAddress], enableWildcardResolver: bool
): SwitchBuilder {.deprecated: "use withWildcardResolver()".} =
## Set the listening addresses of the switch
b.addresses = addresses
b.enableWildcardResolver = enableWildcardResolver
b
proc withAddress*(
b: SwitchBuilder, address: MultiAddress, enableWildcardResolver: bool
): SwitchBuilder {.deprecated: "use withWildcardResolver()".} =
## Set the listening address of the switch
b.withAddresses(@[address], enableWildcardResolver)
proc withAnnouncedAddresses*(
b: SwitchBuilder, addresses: seq[MultiAddress]
): SwitchBuilder =
## Set explicit addresses to advertise to peers, distinct from the
## switch's listening addresses. When non-empty, these replace the output
## of the address mapper chain (the `addressPolicy` filter is still applied).
## Use this to announce a public NAT-mapped address while binding locally.
b.announcedAddrs = addresses
b
proc withAnnouncedAddress*(b: SwitchBuilder, address: MultiAddress): SwitchBuilder =
## Set a single announced address. See `withAnnouncedAddresses`.
b.withAnnouncedAddresses(@[address])
proc withSignedPeerRecord*(b: SwitchBuilder, sendIt = true): SwitchBuilder =
b.sendSignedPeerRecord = sendIt
b
proc withMplex*(
b: SwitchBuilder,
inTimeout = 5.minutes,
outTimeout = 5.minutes,
maxChannCount = 200,
maxBufferedBytes = MaxBufferedBytes,
): SwitchBuilder =
## Uses `Mplex` as a multiplexer
## `Timeout` is the duration after which a inactive connection will be closed
proc newMuxer(conn: RawConn): Muxer =
Mplex.new(conn, inTimeout, outTimeout, maxChannCount, maxBufferedBytes)
doAssert b.muxers.countIt(it.codec == MplexCodec) == 0, "Mplex build multiple times"
b.muxers.add(MuxerProvider.new(newMuxer, MplexCodec))
b
proc withYamux*(
b: SwitchBuilder,
maxChannCount: int = MaxChannelCount,
windowSize: int = YamuxDefaultWindowSize,
inTimeout: Duration = 5.minutes,
outTimeout: Duration = 5.minutes,
): SwitchBuilder =
proc newMuxer(conn: RawConn): Muxer =
Yamux.new(
conn,
maxChannCount = maxChannCount,
windowSize = windowSize,
inTimeout = inTimeout,
outTimeout = outTimeout,
)
doAssert b.muxers.countIt(it.codec == YamuxCodec) == 0, "Yamux build multiple times"
b.muxers.add(MuxerProvider.new(newMuxer, YamuxCodec))
b
proc withNoise*(b: SwitchBuilder): SwitchBuilder =
b.secureManagers.add(SecureProtocol.Noise)
b
proc withNoiseHFS*(b: SwitchBuilder): SwitchBuilder =
## Mount the post-quantum hybrid Noise handshake. Typically combined with
## `withNoise` so a hybrid-capable peer still accepts classical-only peers.
b.secureManagers.add(SecureProtocol.NoiseHFS)
b
proc withTransport*(b: SwitchBuilder, prov: TransportBuilder): SwitchBuilder =
## Use a custom transport
b.transports.add(prov)
b
proc withTcpTransport*(b: SwitchBuilder, flags: set[ServerFlags] = {}): SwitchBuilder =
b.withTransport(
proc(config: TransportConfig): Transport =
TcpTransport.new(flags, config.upgr)
)
proc withWsTransport*(
b: SwitchBuilder,
tlsPrivateKey: TLSPrivateKey = nil,
tlsCertificate: TLSCertificate = nil,
tlsFlags: set[TLSFlags] = {},
flags: set[ServerFlags] = {},
): SwitchBuilder =
b.withTransport(
proc(config: TransportConfig): Transport =
WsTransport.new(
config.upgr,
tlsPrivateKey,
tlsCertificate,
config.autotls,
rng = config.rng,
tlsFlags = tlsFlags,
flags = flags,
)
)
proc withQuicTransport*(
b: SwitchBuilder,
inTimeout: Duration = DefaultChanTimeout,
outTimeout: Duration = DefaultChanTimeout,
engineConfig: QuicEngineConfig = DefaultQuicEngineConfig,
): SwitchBuilder =
b.withTransport(
proc(config: TransportConfig): Transport =
QuicTransport.new(
config.upgr, config.privateKey, config.rng, config.connManager, inTimeout,
outTimeout, engineConfig,
)
)
proc withMemoryTransport*(b: SwitchBuilder): SwitchBuilder =
b.withTransport(
proc(config: TransportConfig): Transport =
MemoryTransport.new(config.upgr, config.rng)
)
proc withRng*(b: SwitchBuilder, rng: Rng): SwitchBuilder =
b.rng = rng
b
proc withConnectionLimits*(b: SwitchBuilder, limits: ConnectionLimits): SwitchBuilder =
## Use `ConnectionLimits.maxTotal` for a shared cap with an optional outbound
## reserve, or `ConnectionLimits.maxInOut` for independent per-direction caps.
b.limits = Opt.some(limits)
b
proc withMaxConnections*(
b: SwitchBuilder, maxConnections: int, outboundReserve: int = 0
): SwitchBuilder =
## Shares the total cap between both directions. An optional `outboundReserve`
## lowers the inbound ceiling, leaving those slots available for outbound dials.
b.limits = Opt.some(ConnectionLimits.maxTotal(maxConnections, outboundReserve))
b
proc withMaxInOut*(b: SwitchBuilder, maxIn: int, maxOut: int): SwitchBuilder =
## Maximum concurrent incoming and outgoing connections.
b.limits = Opt.some(ConnectionLimits.maxInOut(maxIn, maxOut))
b
proc withMaxConnsPerPeer*(b: SwitchBuilder, maxConnsPerPeer: int): SwitchBuilder =
b.maxConnsPerPeer = maxConnsPerPeer
b
proc withWatermarkPolicy*(
b: SwitchBuilder,
lowWater: int,
highWater: int,
gracePeriod: Duration = 0.minutes,
silencePeriod: Duration = 10.seconds,
periodicTrimInterval: Duration = DefaultPeriodicTrimInterval,
): SwitchBuilder =
## Enable hi/lo watermark connection management.
## When connected peers exceed `highWater`, the connection manager trims
## down to `lowWater`, skipping peers within `gracePeriod` and protected peers.
## Can be combined with `withMaxConnections`/`withMaxInOut` to apply both
## a hard semaphore cap and active trimming simultaneously.
doAssert lowWater > 0, "lowWater must be > 0"
doAssert highWater > lowWater, "highWater must be > lowWater"
doAssert periodicTrimInterval > ZeroDuration, "periodicTrimInterval must be > 0"
b.watermark = Opt.some(
WatermarkPolicy(
lowWater: lowWater,
highWater: highWater,
gracePeriod: gracePeriod,
silencePeriod: silencePeriod,
periodicTrimInterval: periodicTrimInterval,
)
)
b
proc withPeerScoring*(
b: SwitchBuilder, scoring: PeerScoring = PeerScoring()
): SwitchBuilder =
## Configure peer scoring parameters.
doAssert scoring.decayResolution > 0.seconds, "decayResolution must be > 0"
b.scoring = scoring
b
proc withPeerStore*(b: SwitchBuilder, capacity: int): SwitchBuilder =
b.peerStoreCapacity = Opt.some(capacity)
b
proc withAddressConfidenceTtls*(
b: SwitchBuilder, ttls: AddressConfidenceTtls
): SwitchBuilder =
## Override the per-confidence TTLs used to expire peer addresses.
b.addressTtls = ttls
b
proc withProtoVersion*(b: SwitchBuilder, protoVersion: string): SwitchBuilder =
b.protoVersion = protoVersion
b
proc withAgentVersion*(b: SwitchBuilder, agentVersion: string): SwitchBuilder =
b.agentVersion = agentVersion
b
proc withNameResolver*(b: SwitchBuilder, nameResolver: NameResolver): SwitchBuilder =
## Use a caller-managed resolver. The switch never starts or stops it.
b.nameResolver = nameResolver
b.nameResolverKind = NameResolverKind.Custom
b.nameServers = @[]
b
proc withDNSNameResolver*(
b: SwitchBuilder, nameServers: seq[TransportAddress]
): SwitchBuilder =
## Create a switch-managed DNS resolver per build, using the supplied servers.
## Replaces any previously configured resolver; an empty list disables DNS queries.
b.nameResolverKind = NameResolverKind.Dns
b.nameServers = nameServers
b.nameResolver = nil
b
proc withSystemNameResolver*(b: SwitchBuilder): SwitchBuilder =
## Create a switch-managed OS resolver per build, with system DNS servers for TXT.
## Replaces any previously configured resolver.
b.nameResolverKind = NameResolverKind.System
b.nameServers = @[]
b.nameResolver = nil
b
proc withDialRanking*(b: SwitchBuilder, enabled: bool = true): SwitchBuilder =
b.dialRanking = enabled
b
proc withDialBackoff*(b: SwitchBuilder, config = DefaultDialBackoff): SwitchBuilder =
## Hold off dialing an address, and a peer, that keeps failing.
b.dialBackoff = Opt.some(config)
b
proc withAutonat*(b: SwitchBuilder, enabled: bool = true): SwitchBuilder =
b.autonatEnabled = enabled
b
proc withAutonatV2Server*(
b: SwitchBuilder, config: AutonatV2Config = AutonatV2Config.new()
): SwitchBuilder =
b.autonatV2ServerConfig = Opt.some(config)
b
proc withNAT*(
b: SwitchBuilder, config: NATConfig, portMapperFactory: PortMapperFactory = nil
): SwitchBuilder =
## Build ``config`` with the `*Config` helpers; call once per distinct concern,
## setting the same concern twice is a programmer error.
var merged = b.natConfig.get(NATConfig())
merged.mergeInto(config)
b.natConfig = Opt.some(merged)
if not portMapperFactory.isNil():
b.natPortMapperFactory = portMapperFactory
b
proc withAutonatV2*(
b: SwitchBuilder,
serviceConfig: AutonatV2ServiceConfig = AutonatV2ServiceConfig.new(),
): SwitchBuilder {.
deprecated:
"use withNAT(autonatConfig(AutonatV2, v2ServiceConfig = Opt.some(serviceConfig)))"
.} =
b.withNAT(autonatConfig(AutonatV2, v2ServiceConfig = Opt.some(serviceConfig)))
proc withHolePunching*(
b: SwitchBuilder, maxNumRelays: int, onReservationHandler: RelayReservationHandler
): SwitchBuilder {.
deprecated: "use withNAT(holePunchingConfig(maxNumRelays, onReservationHandler))"
.} =
b.withNAT(holePunchingConfig(maxNumRelays, onReservationHandler))
proc withAutotls*(
b: SwitchBuilder, config: AutotlsConfig = AutotlsConfig.new()
): SwitchBuilder =
b.autotlsConfig = Opt.some(config)
b
proc withCircuitRelay*(b: SwitchBuilder, r: Relay = Relay.new()): SwitchBuilder =
if r.isNil:
b.circuitRelay = Opt.none(Relay)
else:
b.circuitRelay = Opt.some(r)
b
proc withRendezVous*(
b: SwitchBuilder, config: RendezVousConfig = RendezVousConfig.new()
): SwitchBuilder =
b.rdvConfig = Opt.some(config)
b
proc withKademlia*(
b: SwitchBuilder,
bootstrapNodes: seq[(PeerId, seq[MultiAddress])] = @[],
config: KadDHTConfig = KadDHTConfig.new(),
mode: KadMode = KadMode.Server,
autoMode: AutoModeConfig = AutoModeConfig.init(),
): SwitchBuilder =
b.kad = Opt.some(
KadInfo(
config: config, bootstrapNodes: bootstrapNodes, mode: mode, autoMode: autoMode
)
)
b
proc withIdentifyPusher*(b: SwitchBuilder, enabled: bool = true): SwitchBuilder =
## When enabled, the IdentifyPush protocol is mounted on the
## switch and an `IdentifyPusher` service tracks which connected peers
## advertise IdentifyPush, broadcasting our updated `PeerInfo` to all
## tracked peers whenever it changes.
b.identifyPusherEnabled = enabled
b
proc withAddressManager*(
b: SwitchBuilder, config: AddressManagerConfig
): SwitchBuilder =
## Set the thresholds of the address manager.
b.addressManagerConfig = Opt.some(config)
b
proc withAddressPolicy*(
b: SwitchBuilder, addressPolicy: PeerAddressPolicy
): SwitchBuilder =
## Applies a single address visibility policy across local address
## announcements and all discovery/storage paths configured by the builder.
b.addressPolicy = addressPolicy
b
proc withUndialableAddresses*(b: SwitchBuilder, allow = true): SwitchBuilder =
## Publishes, stores and dials a wildcard host and a port `0`, for a local test only.
b.allowUndialableAddrs = allow
b
proc withPrivateAddressFilter*(b: SwitchBuilder): SwitchBuilder =
## Filter private (RFC1918/link-local) addresses from all peer address
## announcements and incoming peer address records. When enabled:
## - Our node will not announce private addresses to the network
## - Private addresses received from other peers are discarded
## Circuit relay and DNS addresses are never filtered.
b.withAddressPolicy(publicRoutableAddressPolicy)
proc resolveCircuitRelay(b: SwitchBuilder): Opt[Relay] =
b.natConfig.ifValue(natCfg):
if natCfg.holePunching.isSome() and b.circuitRelay.isNone():
return Opt.some(Relay(RelayClient.new()))
b.circuitRelay
proc buildSwitch(b: SwitchBuilder): LPResult[Switch] =
if b.rng.isNil:
b.rng = newRng()
if b.rng.isNil: # newRng could fail
return err("Could not initialize RNG")
let seckey = b.privKey.valueOr:
PrivateKey.random(b.rng).valueOr:
return err(error, "Could not create new private key")
if b.secureManagers.len == 0:
debug "No secure managers configured; using Noise by default"
b.secureManagers.add(SecureProtocol.Noise)
b.resolvedRelay = b.resolveCircuitRelay()
var muxers = b.muxers
b.resolvedRelay.ifValue(relay):
if relay of RelayClient and muxers.len == 0:
# Relay circuits need a stream muxer even when the relay is reached over QUIC.
warn "No stream muxers configured for relay client; using Mplex and Yamux defaults"
muxers.add(
MuxerProvider.new(
proc(conn: RawConn): Muxer =
Mplex.new(conn),
MplexCodec,
)
)
muxers.add(
MuxerProvider.new(
proc(conn: RawConn): Muxer =
Yamux.new(conn),
YamuxCodec,
)
)
var secureManagerInstances: seq[Secure]
# NoiseHFS goes first: multistream-select proposes codecs in list order and
# the first one both peers support wins, so listing `/noise` first would
# make two hybrid-capable peers always settle on the classical handshake.
if SecureProtocol.NoiseHFS in b.secureManagers:
secureManagerInstances.add(
NoiseHFS.new(b.rng, seckey, muxers = muxers.mapIt(it.codec)).Secure
)
if SecureProtocol.Noise in b.secureManagers:
secureManagerInstances.add(
Noise.new(b.rng, seckey, muxers = muxers.mapIt(it.codec)).Secure
)
let peerInfo = ?PeerInfo.tryNew(
seckey, protoVersion = b.protoVersion, agentVersion = b.agentVersion
)
let addressManager =
AddressManager.new(b.addressManagerConfig.get(AddressManagerConfig()))
addressManager.setListenAddrs(b.addresses)
addressManager.setAnnouncedAddrs(b.announcedAddrs)
addressManager.setAddressPolicy(b.addressPolicy)
let identify = Identify.new(peerInfo, b.sendSignedPeerRecord, addressManager)
var peerStore = block:
b.peerStoreCapacity.ifValue(capacity):
PeerStore.new(identify, capacity, b.addressTtls)
else:
PeerStore.new(identify, addressTtls = b.addressTtls)
peerStore.addressPolicy = b.addressPolicy
peerStore.allowUndialableAddrs = b.allowUndialableAddrs
var connManager = ConnManager.new(
maxConnsPerPeer = b.maxConnsPerPeer,
limits = b.limits,
watermark = b.watermark,
scoring = b.scoring,
)
connManager.peerStore = peerStore
let ms = MultistreamSelect.new()
let muxedUpgrade = MuxedUpgrade.new(muxers, secureManagerInstances, ms, connManager)
let nameResolver =
case b.nameResolverKind
of NameResolverKind.Custom:
b.nameResolver
of NameResolverKind.Dns:
NameResolver(DnsResolver.new(b.nameServers, b.rng))
of NameResolverKind.System:
NameResolver(SystemResolver.new(b.rng))
var services: seq[Service]
if b.nameResolverKind != NameResolverKind.Custom:
services.add(NameResolverService(resolver: nameResolver))
var autotlsOpt = Opt.none(AutotlsService)
b.autotlsConfig.ifValue(config):
let autotlsService = AutotlsService.new(b.rng, config)
autotlsOpt = Opt.some(autotlsService)
services.add(autotlsService)
var transports: seq[Transport]
for tProvider in b.transports:
transports.add(
tProvider(
TransportConfig(
upgr: muxedUpgrade,
privateKey: seckey,
autotls: autotlsOpt,
connManager: connManager,
rng: b.rng,
)
)
)
let dialer = Dialer.new(
peerInfo.peerId,
connManager,
peerStore,
transports,
ms,
nameResolver,
dialRanking = b.dialRanking,
dialBackoff = b.dialBackoff,
)
let switch = Switch(
peerInfo: peerInfo,
ms: ms,
transports: transports,
connManager: connManager,
peerStore: peerStore,
dialer: dialer,
nameResolver: nameResolver,
rng: b.rng,
muxedUpgrade: muxedUpgrade,
services: services,
addressManager: addressManager,
)
ok(switch)
func relayClient(circuitRelay: Opt[Relay]): RelayClient =
circuitRelay.ifValue(relay):
if relay of RelayClient:
return RelayClient(relay)
nil
proc addServices(b: SwitchBuilder, switch: Switch) =
if b.enableWildcardResolver:
switch.services.add(WildcardAddressResolverService.new())
b.natConfig.ifValue(natCfg):
switch.services.add(
NATService.new(
natCfg, b.rng, b.natPortMapperFactory, b.resolvedRelay.relayClient()
)
)
if b.identifyPusherEnabled:
switch.services.add(IdentifyPusher.new(switch))
if b.mdnsEnabled:
switch.services.add(
MdnsService.new(
b.mdnsCallback,
queryInterval = b.mdnsQueryInterval,
maxPendingCallbacks = b.mdnsMaxPendingCallbacks,
)
)
proc mountProtocols(b: SwitchBuilder, switch: Switch): LPResult[void] =
if not switch.peerStore.identify.isNil:
?switch.tryMount(switch.peerStore.identify)
b.rdvConfig.ifValue(rdvCfg):
let rend = RendezVous.new(b.rng, rdvCfg)
rend.setup(switch)
?switch.tryMount(rend)
b.autonatV2ServerConfig.ifValue(config):
?switch.tryMount(AutonatV2.new(switch, config = config))
if b.autonatEnabled:
?switch.tryMount(Autonat.new(switch))
b.resolvedRelay.ifValue(relay):
if relay of RelayClient:
switch.addTransport(RelayTransport.new(RelayClient(relay), switch.muxedUpgrade))
relay.setup(switch)
?switch.tryMount(relay)
b.kad.ifValue(kadInfo):
var config = kadInfo.config
config.addressPolicy = b.addressPolicy
let kad = KadDHT.new(
switch,
bootstrapNodes = kadInfo.bootstrapNodes,
config = config,
rng = b.rng,
# Auto starts as a client until autonat proves the node reachable.
isServer = kadInfo.mode == KadMode.Server,
)
?switch.tryMount(kad)
if kadInfo.mode == KadMode.Auto:
var wired = false
switch.natService().ifValue(nat):
let current = proc(): NetworkReachability {.gcsafe, raises: [].} =
nat.networkReachability()
wired =
nat.addReachabilityHandler(kad.enableAutoMode(current, kadInfo.autoMode))
if not wired:
warn "Kad-DHT auto mode has no reachability service; it stays a client",
hint = "configure withNAT reachability or hole-punching"
ok()
proc build*(b: SwitchBuilder): Switch {.raises: [LPError].} =
b.natConfig.ifValue(natCfg):
validateNATConfig(natCfg, b.circuitRelay).onErrorRaise(LPError)
let switch = b.buildSwitch().valueOrRaise(LPError)
b.addServices(switch)
b.mountProtocols(switch).onErrorRaise(LPError)
switch