weirdnet-net 0.2.0

Weirdnet networking: a libp2p node (TCP, QUIC, Noise, Yamux, mDNS, Kademlia, relays, hole punching, AutoNAT) carrying the application's own request and response types, signed key-exchange offers and answers with short codes, invitation tokens and links, sealed exchange messaging, node identities, user certificates and cards, under versioned identifier profiles.
Documentation
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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
//! The libp2p node: TCP and QUIC (or an in-memory transport for tests) with Noise and
//! Yamux; mDNS on the local network; Kademlia, identify and ping; relay client and
//! (opt-in) relay server with DCUtR hole punching; AutoNAT; and request-response on
//! the profile's protocol id, carrying the application's own request and response types
//! (CBOR).
//!
//! The swarm runs on its own thread with a small Tokio runtime. [`Node`] is a blocking
//! handle (the CLI and TUI are synchronous): requests wait for their answer. Requests
//! that come in are answered by a [`Handler`] on Tokio's blocking pool.
use crate::addr::{addr_peer, reach_rank, routable, shareable};
use crate::error::{NetError, Result};
use crate::names::{Entry, Lookup, Names, NamesRequest, NamesResponse};
use crate::profile::Profile;
use futures::StreamExt;
use libp2p::core::muxing::StreamMuxerBox;
use libp2p::core::transport::{Boxed, MemoryTransport, Transport};
use libp2p::core::upgrade::Version;
use libp2p::identity::Keypair;
use libp2p::kad::{self, store::MemoryStore, store::RecordStore};
use libp2p::multiaddr::Protocol;
use libp2p::request_response::{self, OutboundRequestId, ProtocolSupport};
use libp2p::swarm::behaviour::toggle::Toggle;
use libp2p::swarm::{NetworkBehaviour, SwarmEvent};
use libp2p::{Multiaddr, PeerId, StreamProtocol, Swarm, autonat, dcutr, identify, mdns, noise, ping, relay, tcp, yamux};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};

const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
const REQUEST_MAX: u64 = 8 * 1024 * 1024;
const RESPONSE_MAX: u64 = 256 * 1024 * 1024;

/// How a node runs.
#[derive(Debug, Clone, Default)]
pub struct NodeConfig {
    /// Addresses to listen on (none: only dial out).
    pub listen: Vec<Multiaddr>,
    /// Find and announce peers on the local network.
    pub mdns: bool,
    /// Relay traffic for other nodes (and say so).
    pub relay_server: bool,
    /// Kademlia bootstrap nodes (`/ip4/…/tcp/…/p2p/…`).
    pub bootstrap: Vec<Multiaddr>,
    /// Relays to reserve a slot on (`/…/p2p/RELAY`); reachable through them behind NAT.
    pub relays: Vec<Multiaddr>,
    /// The in-memory transport (tests) instead of TCP and QUIC.
    pub memory: bool,
    /// This node's label (in identify; empty: none).
    pub label: String,
    /// Addresses others reach us at from outside (a DNS name or public IP forwarded to
    /// this node), announced and put in invites before the local ones.
    pub external: Vec<Multiaddr>,
    /// The application's version, in the identify agent (`NAME/VERSION`); empty: this
    /// crate's version.
    pub version: String,
    /// What the relay server (`relay_server`) allows; the default is libp2p's.
    pub relay_limits: RelayLimits,
    /// Serve the names protocol (rendezvous for signed peer records) from this store.
    pub names_server: Option<Names>,
    /// Names servers to register with and look users up on (`…/p2p/ID`), besides the
    /// relays this node holds a reservation on.
    pub names_servers: Vec<Multiaddr>,
}

/// Limits of the relay server: how many reservations and circuits it holds, and how long
/// and how much one circuit may carry. [`RelayLimits::default`] keeps libp2p's defaults
/// (circuits for hole punching and small requests: 2 minutes, 128 KiB);
/// [`RelayLimits::unlimited`] caps nothing, so circuits carry data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RelayLimits {
    /// Reservations held at once, and per peer.
    pub max_reservations: usize,
    pub max_reservations_per_peer: usize,
    /// How long a reservation lasts before the client renews it.
    pub reservation_duration: Duration,
    /// Circuits open at once, and per peer.
    pub max_circuits: usize,
    pub max_circuits_per_peer: usize,
    /// How long one circuit may stay open (at most `u32::MAX` seconds).
    pub max_circuit_duration: Duration,
    /// How many bytes one circuit may carry in each direction; 0: no limit.
    pub max_circuit_bytes: u64,
    /// libp2p's rate limiters on new reservations and circuits (per peer and per IP).
    pub rate_limits: bool,
}

impl Default for RelayLimits {
    /// libp2p's defaults.
    fn default() -> Self {
        let c = relay::Config::default();
        RelayLimits {
            max_reservations: c.max_reservations,
            max_reservations_per_peer: c.max_reservations_per_peer,
            reservation_duration: c.reservation_duration,
            max_circuits: c.max_circuits,
            max_circuits_per_peer: c.max_circuits_per_peer,
            max_circuit_duration: c.max_circuit_duration,
            max_circuit_bytes: c.max_circuit_bytes,
            rate_limits: true,
        }
    }
}

impl RelayLimits {
    /// Longest circuit duration libp2p accepts.
    pub const MAX_CIRCUIT_DURATION: Duration = Duration::from_secs(u32::MAX as u64);

    /// No caps: as many reservations and circuits as clients ask for, no byte limit, the
    /// longest circuit libp2p accepts, and no rate limiters. Reservations still last an hour
    /// before the client renews them.
    pub fn unlimited() -> Self {
        RelayLimits {
            max_reservations: usize::MAX,
            max_reservations_per_peer: usize::MAX,
            max_circuits: usize::MAX,
            max_circuits_per_peer: usize::MAX,
            max_circuit_duration: Self::MAX_CIRCUIT_DURATION,
            max_circuit_bytes: 0,
            rate_limits: false,
            ..Self::default()
        }
    }

    /// Whether nothing is capped (see [`RelayLimits::unlimited`]).
    pub fn is_unlimited(&self) -> bool {
        *self == Self::unlimited()
    }

    /// Refuse limits libp2p cannot apply (a zero count or duration, or a circuit duration
    /// over `u32::MAX` seconds).
    pub fn check(&self) -> Result<()> {
        if self.max_reservations == 0 || self.max_reservations_per_peer == 0 || self.max_circuits == 0 || self.max_circuits_per_peer == 0 {
            return Err(NetError::invalid("relay limits", "reservation and circuit counts must be at least 1"));
        }
        if self.reservation_duration.is_zero() || self.max_circuit_duration.is_zero() {
            return Err(NetError::invalid("relay limits", "durations must be longer than zero"));
        }
        if self.max_circuit_duration > Self::MAX_CIRCUIT_DURATION {
            return Err(NetError::invalid("relay limits", "a circuit may last at most u32::MAX seconds"));
        }
        Ok(())
    }

    fn config(&self) -> relay::Config {
        let mut c = relay::Config {
            max_reservations: self.max_reservations,
            max_reservations_per_peer: self.max_reservations_per_peer,
            reservation_duration: self.reservation_duration,
            max_circuits: self.max_circuits,
            max_circuits_per_peer: self.max_circuits_per_peer,
            max_circuit_duration: self.max_circuit_duration,
            max_circuit_bytes: self.max_circuit_bytes,
            ..relay::Config::default()
        };
        if !self.rate_limits {
            c.reservation_rate_limiters.clear();
            c.circuit_src_rate_limiters.clear();
        }
        c
    }
}

impl NodeConfig {
    /// TCP and QUIC on every interface, IPv4 and IPv6, on `port`.
    pub fn default_listen(port: u16) -> Vec<Multiaddr> {
        [
            format!("/ip4/0.0.0.0/tcp/{port}"),
            format!("/ip4/0.0.0.0/udp/{port}/quic-v1"),
            format!("/ip6/::/tcp/{port}"),
            format!("/ip6/::/udp/{port}/quic-v1"),
        ]
        .iter()
        .filter_map(|a| a.parse().ok())
        .collect()
    }
}

/// A peer seen by the node, for the handler to remember.
#[derive(Debug, Clone)]
pub struct Sighting {
    pub peer: PeerId,
    pub addrs: Vec<String>,
    pub caps: Option<Vec<String>>,
    pub agent: Option<String>,
    pub source: &'static str,
}

/// What a node carries: the application's request and response types (sent as CBOR).
pub trait Message: Serialize + DeserializeOwned + std::fmt::Debug + Clone + Send + 'static {}
impl<T: Serialize + DeserializeOwned + std::fmt::Debug + Clone + Send + 'static> Message for T {}

/// Answers requests from peers. The peer id is the one Noise authenticated.
pub trait Handler<Q, R>: Send + Sync + 'static {
    fn request(&self, from: &PeerId, req: Q) -> R;
    /// A peer was discovered or identified.
    fn seen(&self, _s: Sighting) {}
}

/// What the node is doing.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Status {
    pub peer_id: String,
    pub listening: Vec<String>,
    pub external: Vec<String>,
    pub connected: Vec<String>,
    /// AutoNAT: `public`, `private` or `unknown`.
    pub nat: String,
    /// Relays holding a reservation for us.
    pub reservations: Vec<String>,
    pub relay_server: bool,
    pub mdns: bool,
    pub started_at: i64,
}

// rustc 1.100 flags code the `NetworkBehaviour` derive generates (matches on
// uninhabited events) as unreachable; the allow has to sit on a module to reach it.
#[allow(unreachable_code)]
mod wire {
    use super::*;

    #[derive(NetworkBehaviour)]
    pub(super) struct Behaviour<Q: Message, R: Message> {
        pub(super) rr: request_response::cbor::Behaviour<Q, R>,
        pub(super) names: request_response::cbor::Behaviour<NamesRequest, NamesResponse>,
        pub(super) identify: identify::Behaviour,
        pub(super) ping: ping::Behaviour,
        pub(super) kad: kad::Behaviour<MemoryStore>,
        pub(super) mdns: Toggle<mdns::tokio::Behaviour>,
        pub(super) relay_client: relay::client::Behaviour,
        pub(super) relay_server: Toggle<relay::Behaviour>,
        pub(super) dcutr: dcutr::Behaviour,
        pub(super) autonat: autonat::Behaviour,
    }
}
use wire::{Behaviour, BehaviourEvent};

enum Cmd<Q, R> {
    Request { peer: PeerId, addrs: Vec<Multiaddr>, wire: Q, reply: oneshot::Sender<Result<R>> },
    Names { peer: PeerId, addrs: Vec<Multiaddr>, req: NamesRequest, reply: oneshot::Sender<Result<NamesResponse>> },
    PutEntry { entry: Entry, reply: oneshot::Sender<Result<()>> },
    GetEntries { user: String, reply: oneshot::Sender<Result<Vec<Entry>>> },
    FindPeer { peer: PeerId, reply: oneshot::Sender<Result<Vec<Multiaddr>>> },
    KnownAddrs { reply: oneshot::Sender<Result<Vec<(PeerId, Multiaddr)>>> },
    Dial { addr: Multiaddr, reply: oneshot::Sender<Result<PeerId>> },
    Listen { addr: Multiaddr, reply: oneshot::Sender<Result<Multiaddr>> },
    AddRelay { addr: Multiaddr },
    Stop,
}

/// A running node.
pub struct Node<Q: Message, R: Message> {
    peer_id: PeerId,
    profile: &'static Profile,
    names_list: Vec<Multiaddr>,
    tx: mpsc::UnboundedSender<Cmd<Q, R>>,
    status: Arc<Mutex<Status>>,
    thread: Option<std::thread::JoinHandle<()>>,
}

fn net_err(e: impl std::fmt::Display) -> NetError {
    NetError::net(e)
}

fn stopped() -> NetError {
    NetError::Network("the node has stopped".into())
}

fn behaviour<Q: Message, R: Message>(
    p: &Profile,
    key: &Keypair,
    relay_client: relay::client::Behaviour,
    cfg: &NodeConfig,
) -> Result<Behaviour<Q, R>> {
    let peer = key.public().to_peer_id();
    let rr = request_response::cbor::Behaviour::with_codec(
        request_response::cbor::codec::Codec::default().set_request_size_maximum(REQUEST_MAX).set_response_size_maximum(RESPONSE_MAX),
        [(StreamProtocol::new(p.protocol), ProtocolSupport::Full)],
        request_response::Config::default().with_request_timeout(REQUEST_TIMEOUT),
    );
    let version = if cfg.version.is_empty() { env!("CARGO_PKG_VERSION") } else { cfg.version.as_str() };
    let agent = p.agent(version, &cfg.label);
    // A relay with explicit external addresses announces only those, not every
    // interface it listens on (private VPC and loopback ones are useless to clients).
    let hide = cfg.relay_server && !cfg.external.is_empty();
    let identify =
        identify::Behaviour::new(identify::Config::new(p.identify.into(), key.public()).with_agent_version(agent).with_hide_listen_addrs(hide));
    let mut kcfg = kad::Config::new(StreamProtocol::new(p.kad));
    kcfg.set_query_timeout(Duration::from_secs(30));
    // every record and provider a peer puts is checked first (peer records, relay keys)
    kcfg.set_record_filtering(kad::StoreInserts::FilterBoth);
    let names = request_response::cbor::Behaviour::with_codec(
        request_response::cbor::codec::Codec::default().set_request_size_maximum(64 * 1024).set_response_size_maximum(64 * 1024),
        [(StreamProtocol::new(p.names), if cfg.names_server.is_some() { ProtocolSupport::Full } else { ProtocolSupport::Outbound })],
        request_response::Config::default().with_request_timeout(Duration::from_secs(20)),
    );
    let kad = kad::Behaviour::with_config(peer, MemoryStore::new(peer), kcfg);
    let mdns = if cfg.mdns && !cfg.memory { Some(mdns::tokio::Behaviour::new(mdns::Config::default(), peer).map_err(net_err)?) } else { None };
    let relay_server = cfg.relay_server.then(|| relay::Behaviour::new(peer, cfg.relay_limits.config()));
    let autonat = autonat::Behaviour::new(peer, autonat::Config { only_global_ips: !cfg.memory, ..Default::default() });
    Ok(Behaviour {
        rr,
        names,
        identify,
        ping: ping::Behaviour::new(ping::Config::new()),
        kad,
        mdns: mdns.into(),
        relay_client,
        relay_server: relay_server.into(),
        dcutr: dcutr::Behaviour::new(peer),
        autonat,
    })
}

type BoxErr = Box<dyn std::error::Error + Send + Sync>;

fn memory_transport(key: &Keypair) -> std::result::Result<Boxed<(PeerId, StreamMuxerBox)>, BoxErr> {
    Ok(MemoryTransport::default()
        .upgrade(Version::V1)
        .authenticate(noise::Config::new(key).map_err(|e| Box::new(e) as BoxErr)?)
        .multiplex(yamux::Config::default())
        .timeout(Duration::from_secs(20))
        .boxed())
}

fn build_swarm<Q: Message, R: Message>(p: &'static Profile, key: Keypair, cfg: &NodeConfig) -> Result<Swarm<Behaviour<Q, R>>> {
    let idle = |c: libp2p::swarm::Config| c.with_idle_connection_timeout(Duration::from_secs(120));
    let swarm = if cfg.memory {
        let cfg2 = cfg.clone();
        libp2p::SwarmBuilder::with_existing_identity(key)
            .with_tokio()
            .with_other_transport(memory_transport)
            .map_err(net_err)?
            .with_relay_client(noise::Config::new, yamux::Config::default)
            .map_err(net_err)?
            .with_behaviour(move |key, relay| behaviour(p, key, relay, &cfg2).map_err(|e| Box::new(e) as BoxErr))
            .map_err(net_err)?
            .with_swarm_config(idle)
            .build()
    } else {
        let cfg2 = cfg.clone();
        libp2p::SwarmBuilder::with_existing_identity(key)
            .with_tokio()
            .with_tcp(tcp::Config::default().nodelay(true), noise::Config::new, yamux::Config::default)
            .map_err(net_err)?
            .with_quic()
            .with_dns()
            .map_err(net_err)?
            .with_relay_client(noise::Config::new, yamux::Config::default)
            .map_err(net_err)?
            .with_behaviour(move |key, relay| behaviour(p, key, relay, &cfg2).map_err(|e| Box::new(e) as BoxErr))
            .map_err(net_err)?
            .with_swarm_config(idle)
            .build()
    };
    Ok(swarm)
}

impl<Q: Message, R: Message> Node<Q, R> {
    /// Start a node speaking `profile`; returns once its listeners are up (or failed).
    pub fn start(profile: &'static Profile, key: Keypair, cfg: NodeConfig, handler: Arc<dyn Handler<Q, R>>) -> Result<Self> {
        if cfg.relay_server {
            cfg.relay_limits.check()?;
        }
        let peer_id = key.public().to_peer_id();
        let status = Arc::new(Mutex::new(Status {
            peer_id: peer_id.to_string(),
            nat: "unknown".into(),
            relay_server: cfg.relay_server,
            mdns: cfg.mdns && !cfg.memory,
            started_at: crate::now_ms(),
            ..Default::default()
        }));
        let (tx, rx) = mpsc::unbounded_channel();
        let (ready_tx, ready_rx) = std::sync::mpsc::channel::<Result<()>>();
        let st = status.clone();
        let names_list = cfg.names_servers.clone();
        let thread = std::thread::Builder::new()
            .name(profile.thread.into())
            .spawn(move || {
                let rt = match tokio::runtime::Builder::new_multi_thread()
                    .worker_threads(2)
                    .enable_all()
                    .thread_name(format!("{}-rt", profile.thread))
                    .build()
                {
                    Ok(rt) => rt,
                    Err(e) => {
                        let _ = ready_tx.send(Err(net_err(e)));
                        return;
                    }
                };
                rt.block_on(async move {
                    let swarm = match build_swarm(profile, key, &cfg) {
                        Ok(mut s) => {
                            for a in &cfg.external {
                                s.add_external_address(a.clone());
                            }
                            s
                        }
                        Err(e) => {
                            let _ = ready_tx.send(Err(e));
                            return;
                        }
                    };
                    let mut l = Loop::new(profile, swarm, cfg, handler, st);
                    l.run(rx, ready_tx).await;
                });
                rt.shutdown_timeout(Duration::from_secs(2));
            })
            .map_err(net_err)?;
        match ready_rx.recv_timeout(Duration::from_secs(20)) {
            Ok(Ok(())) => Ok(Node { peer_id, profile, names_list, tx, status, thread: Some(thread) }),
            Ok(Err(e)) => {
                let _ = thread.join();
                Err(e)
            }
            Err(_) => Err(NetError::Network("the node did not start in time".into())),
        }
    }

    pub fn peer_id(&self) -> PeerId {
        self.peer_id
    }

    pub fn status(&self) -> Status {
        self.status.lock().map(|s| s.clone()).unwrap_or_default()
    }

    /// Addresses others can use to reach this node (with `/p2p/ID`).
    pub fn reachable_addrs(&self) -> Vec<String> {
        let s = self.status();
        let mut v: Vec<String> = vec![];
        for a in s.external.iter().chain(s.listening.iter()) {
            // a circuit through a relay is only useful if the relay's own address is routable
            if let Ok(m) = a.parse::<Multiaddr>()
                && shareable(&m)
                && (!m.iter().any(|p| p == Protocol::P2pCircuit) || routable(&m))
            {
                let full = if addr_peer(&m).is_some() { m } else { m.with(Protocol::P2p(self.peer_id)) };
                let t = full.to_string();
                if !v.contains(&t) {
                    v.push(t);
                }
            }
        }
        v
    }

    fn call<T>(&self, make: impl FnOnce(oneshot::Sender<Result<T>>) -> Cmd<Q, R>, wait: Duration) -> Result<T> {
        let (tx, rx) = oneshot::channel();
        self.tx.send(make(tx)).map_err(|_| stopped())?;
        let deadline = std::time::Instant::now() + wait;
        let mut rx = rx;
        loop {
            match rx.try_recv() {
                Ok(r) => return r,
                Err(oneshot::error::TryRecvError::Closed) => return Err(stopped()),
                Err(oneshot::error::TryRecvError::Empty) => {
                    if std::time::Instant::now() > deadline {
                        return Err(NetError::Network("timed out".into()));
                    }
                    std::thread::sleep(Duration::from_millis(5));
                }
            }
        }
    }

    /// Send a request and wait for the answer. `addrs` are tried if not connected yet.
    pub fn request(&self, peer: PeerId, addrs: &[Multiaddr], wire: Q) -> Result<R> {
        let addrs = addrs.to_vec();
        self.call(|reply| Cmd::Request { peer, addrs, wire, reply }, REQUEST_TIMEOUT + Duration::from_secs(5))
    }

    /// Ask a names server (a relay, usually) something; `addrs` are tried if not connected.
    pub fn names_request(&self, server: PeerId, addrs: &[Multiaddr], req: NamesRequest) -> Result<NamesResponse> {
        let addrs = addrs.to_vec();
        self.call(|reply| Cmd::Names { peer: server, addrs, req, reply }, Duration::from_secs(30))
    }

    /// Register a record or withdrawal on a names server.
    pub fn register(&self, server: PeerId, addrs: &[Multiaddr], entry: Entry) -> Result<()> {
        match self.names_request(server, addrs, NamesRequest::Register(Box::new(entry)))? {
            NamesResponse::Registered => Ok(()),
            NamesResponse::Refused(why) => Err(NetError::Network(format!("the names server refused: {why}"))),
            NamesResponse::Found(_) => Err(NetError::Network("unexpected answer from the names server".into())),
        }
    }

    /// A user's entry on one names server.
    pub fn discover(&self, server: PeerId, addrs: &[Multiaddr], user: &str) -> Result<Option<Entry>> {
        match self.names_request(server, addrs, NamesRequest::Discover { user_id: user.into() })? {
            NamesResponse::Found(e) => Ok(e.map(|e| *e)),
            NamesResponse::Refused(why) => Err(NetError::Network(format!("the names server refused: {why}"))),
            NamesResponse::Registered => Err(NetError::Network("unexpected answer from the names server".into())),
        }
    }

    /// Put a record or withdrawal in the DHT (checked first, like every storing node does).
    /// Records belong in the DHT only while the device hosts something public or private.
    pub fn put_entry(&self, entry: Entry) -> Result<()> {
        self.call(|reply| Cmd::PutEntry { entry, reply }, Duration::from_secs(40))
    }

    /// Every entry the DHT returns for a user (unchecked; see [`Profile::newest`]).
    pub fn get_entries(&self, user: &str) -> Result<Vec<Entry>> {
        let user = user.to_string();
        self.call(|reply| Cmd::GetEntries { user, reply }, Duration::from_secs(40))
    }

    /// Where a peer is, by its key alone: what the DHT knows of it.
    pub fn find_peer(&self, peer: PeerId) -> Result<Vec<Multiaddr>> {
        self.call(|reply| Cmd::FindPeer { peer, reply }, Duration::from_secs(40))
    }

    /// Names servers to ask: the configured ones and the relays holding our reservation.
    fn names_servers(&self) -> Vec<(PeerId, Vec<Multiaddr>)> {
        let known = self.call(|reply| Cmd::KnownAddrs { reply }, Duration::from_secs(5)).unwrap_or_default();
        let mut out: Vec<(PeerId, Vec<Multiaddr>)> = vec![];
        let reserved: Vec<PeerId> = self.status().reservations.iter().filter_map(|r| r.parse().ok()).collect();
        for (p, a) in known.into_iter() {
            if reserved.contains(&p) || self.names_list.iter().any(|n| addr_peer(n) == Some(p)) {
                match out.iter_mut().find(|(q, _)| *q == p) {
                    Some((_, v)) => v.push(a),
                    None => out.push((p, vec![a])),
                }
            }
        }
        for n in &self.names_list {
            if let Some(p) = addr_peer(n)
                && !out.iter().any(|(q, _)| *q == p)
            {
                out.push((p, vec![n.clone()]));
            }
        }
        out
    }

    /// Register an entry with every names server this node uses (its relays and the
    /// configured ones); returns how many took it.
    pub fn register_everywhere(&self, entry: &Entry) -> usize {
        self.names_servers().into_iter().filter(|(p, a)| self.register(*p, a, entry.clone()).is_ok()).count()
    }

    /// Find a user's freshest valid record: on this node's names servers, then in the DHT.
    pub fn lookup(&self, user: &str) -> Lookup {
        let mut found: Vec<Entry> = vec![];
        for (p, a) in self.names_servers() {
            if let Ok(Some(e)) = self.discover(p, &a, user) {
                found.push(e);
            }
        }
        if let Ok(v) = self.get_entries(user) {
            found.extend(v);
        }
        self.profile.newest(user, &found, crate::now_ms())
    }

    /// Send a request to a peer known only by its key: when not connected, find its
    /// addresses in the DHT and try circuits through this node's relays and names servers.
    pub fn request_key(&self, peer: PeerId, wire: Q) -> Result<R> {
        if self.status().connected.contains(&peer.to_string()) {
            return self.request(peer, &[], wire);
        }
        let mut addrs = self.find_peer(peer).unwrap_or_default();
        for (_, a) in self.names_servers() {
            for base in a {
                let base: Multiaddr = base.iter().take_while(|p| *p != Protocol::P2pCircuit).collect();
                addrs.push(base.with(Protocol::P2pCircuit).with(Protocol::P2p(peer)));
            }
        }
        self.request(peer, &addrs, wire)
    }

    /// Send a request to a user's node: look up its record and dial its addresses
    /// (circuits and direct ones together). Returns the node that answered.
    pub fn request_user(&self, user: &str, wire: Q) -> Result<(PeerId, R)> {
        match self.lookup(user) {
            Lookup::Found(r) => {
                let peer: PeerId = r.cert.peer_id.parse().map_err(|_| NetError::invalid("peer record", "bad peer id"))?;
                let addrs = crate::addr::parse_addrs(&r.addrs);
                Ok((peer, self.request(peer, &addrs, wire)?))
            }
            Lookup::Withdrawn(_) => Err(NetError::Network(format!("{user} withdrew its record"))),
            Lookup::NotFound => Err(NetError::Network(format!("no record for {user}"))),
        }
    }

    /// Connect to an address; returns the peer there.
    pub fn dial(&self, addr: Multiaddr) -> Result<PeerId> {
        self.call(|reply| Cmd::Dial { addr, reply }, Duration::from_secs(30))
    }

    /// Listen on one more address; returns the address it got.
    pub fn listen(&self, addr: Multiaddr) -> Result<Multiaddr> {
        self.call(|reply| Cmd::Listen { addr, reply }, Duration::from_secs(20))
    }

    /// Reserve a slot on a relay (`…/p2p/RELAY`).
    pub fn add_relay(&self, addr: Multiaddr) -> Result<()> {
        self.tx.send(Cmd::AddRelay { addr }).map_err(|_| stopped())
    }

    /// Whether the node thread still runs.
    pub fn running(&self) -> bool {
        self.thread.as_ref().is_some_and(|t| !t.is_finished())
    }

    pub fn stop(mut self) {
        self.shutdown();
    }

    /// Ask the node to stop without waiting (others may still hold it).
    pub fn halt(&self) {
        let _ = self.tx.send(Cmd::Stop);
    }

    fn shutdown(&mut self) {
        let _ = self.tx.send(Cmd::Stop);
        if let Some(t) = self.thread.take() {
            let _ = t.join();
        }
    }
}

impl<Q: Message, R: Message> Drop for Node<Q, R> {
    fn drop(&mut self) {
        self.shutdown();
    }
}

/// A DHT lookup collecting entries, and who waits for them.
type Gathering = (Vec<Entry>, oneshot::Sender<Result<Vec<Entry>>>);
/// A DHT search for one peer's addresses.
type Finding = (PeerId, oneshot::Sender<Result<Vec<Multiaddr>>>);

struct Loop<Q: Message, R: Message> {
    profile: &'static Profile,
    swarm: Swarm<Behaviour<Q, R>>,
    cfg: NodeConfig,
    handler: Arc<dyn Handler<Q, R>>,
    status: Arc<Mutex<Status>>,
    pending: HashMap<OutboundRequestId, oneshot::Sender<Result<R>>>,
    dials: Vec<(Multiaddr, Option<PeerId>, oneshot::Sender<Result<PeerId>>)>,
    listens: HashMap<libp2p::core::transport::ListenerId, oneshot::Sender<Result<Multiaddr>>>,
    relays: HashSet<PeerId>,
    relay_listening: HashSet<PeerId>,
    /// Each relay's circuit listener and when it was asked for (to retry a stuck one).
    relay_listeners: HashMap<PeerId, (Multiaddr, libp2p::core::transport::ListenerId, std::time::Instant)>,
    resp_tx: mpsc::UnboundedSender<(request_response::ResponseChannel<R>, R)>,
    resp_rx: mpsc::UnboundedReceiver<(request_response::ResponseChannel<R>, R)>,
    names_pending: HashMap<OutboundRequestId, oneshot::Sender<Result<NamesResponse>>>,
    names_tx: mpsc::UnboundedSender<(request_response::ResponseChannel<NamesResponse>, NamesResponse)>,
    names_rx: mpsc::UnboundedReceiver<(request_response::ResponseChannel<NamesResponse>, NamesResponse)>,
    puts: HashMap<kad::QueryId, oneshot::Sender<Result<()>>>,
    gets: HashMap<kad::QueryId, Gathering>,
    finds: HashMap<kad::QueryId, Finding>,
    addr_book: HashMap<PeerId, Vec<Multiaddr>>,
}

impl<Q: Message, R: Message> Loop<Q, R> {
    fn new(
        profile: &'static Profile,
        swarm: Swarm<Behaviour<Q, R>>,
        cfg: NodeConfig,
        handler: Arc<dyn Handler<Q, R>>,
        status: Arc<Mutex<Status>>,
    ) -> Self {
        let (resp_tx, resp_rx) = mpsc::unbounded_channel();
        let (names_tx, names_rx) = mpsc::unbounded_channel();
        Loop {
            profile,
            swarm,
            cfg,
            handler,
            status,
            pending: HashMap::new(),
            dials: vec![],
            listens: HashMap::new(),
            relays: HashSet::new(),
            relay_listening: HashSet::new(),
            relay_listeners: HashMap::new(),
            resp_tx,
            resp_rx,
            names_pending: HashMap::new(),
            names_tx,
            names_rx,
            puts: HashMap::new(),
            gets: HashMap::new(),
            finds: HashMap::new(),
            addr_book: HashMap::new(),
        }
    }

    fn update(&self, f: impl FnOnce(&mut Status)) {
        if let Ok(mut s) = self.status.lock() {
            f(&mut s);
        }
    }

    fn refresh(&self) {
        let connected: Vec<String> = self.swarm.connected_peers().map(|p| p.to_string()).collect();
        let listening: Vec<String> = self.swarm.listeners().map(|a| a.to_string()).collect();
        let external: Vec<String> = self.swarm.external_addresses().map(|a| a.to_string()).collect();
        self.update(|s| {
            s.connected = connected;
            s.listening = listening;
            s.external = external;
        });
    }

    fn seen(&self, s: Sighting) {
        let h = self.handler.clone();
        tokio::task::spawn_blocking(move || h.seen(s));
    }

    async fn run(&mut self, mut rx: mpsc::UnboundedReceiver<Cmd<Q, R>>, ready: std::sync::mpsc::Sender<Result<()>>) {
        // listen
        let mut waiting = 0usize;
        let mut ready = Some(ready);
        for a in self.cfg.listen.clone() {
            match self.swarm.listen_on(a.clone()) {
                Ok(_) => waiting += 1,
                Err(e) => tracing::warn!("network: cannot listen on {a}: {e}"),
            }
        }
        if !self.cfg.listen.is_empty() && waiting == 0 {
            if let Some(r) = ready.take() {
                let _ = r.send(Err(NetError::Network("could not listen on any address".into())));
            }
            return;
        }
        // relays first: a reservation dials its relay, and a second dial to the same peer
        // already under way would make the relay client skip its own
        for r in self.cfg.relays.clone() {
            self.add_relay(r);
        }
        for b in self.cfg.bootstrap.clone() {
            if let Some(p) = addr_peer(&b) {
                self.swarm.behaviour_mut().kad.add_address(&p, b.clone());
                if !self.relay_listening.contains(&p) {
                    let _ = self.swarm.dial(b);
                }
            }
        }
        if self.cfg.relay_server {
            self.swarm.behaviour_mut().kad.set_mode(Some(kad::Mode::Server));
        }
        if waiting == 0
            && let Some(r) = ready.take()
        {
            let _ = r.send(Ok(()));
        }
        let ready_deadline = tokio::time::sleep(Duration::from_secs(5));
        tokio::pin!(ready_deadline);
        let mut tick = tokio::time::interval(Duration::from_secs(60));
        let mut check = tokio::time::interval(Duration::from_secs(1));
        loop {
            tokio::select! {
                cmd = rx.recv() => match cmd {
                    None | Some(Cmd::Stop) => break,
                    Some(c) => self.command(c),
                },
                Some((ch, resp)) = self.resp_rx.recv() => {
                    let _ = self.swarm.behaviour_mut().rr.send_response(ch, resp);
                }
                Some((ch, resp)) = self.names_rx.recv() => {
                    let _ = self.swarm.behaviour_mut().names.send_response(ch, resp);
                }
                ev = self.swarm.select_next_some() => {
                    let new_listen = matches!(ev, SwarmEvent::NewListenAddr { .. });
                    self.event(ev);
                    if new_listen && waiting > 0 {
                        waiting -= 1;
                        if waiting == 0 && let Some(r) = ready.take() {
                            let _ = r.send(Ok(()));
                        }
                    }
                }
                _ = &mut ready_deadline, if ready.is_some() => {
                    if let Some(r) = ready.take() {
                        let _ = r.send(Ok(()));
                    }
                }
                _ = tick.tick() => self.periodic(),
                _ = check.tick() => self.retry_stuck_reservations(),
            }
        }
        for (_, tx) in self.pending.drain() {
            let _ = tx.send(Err(NetError::Network("the node stopped".into())));
        }
        for (_, tx) in self.names_pending.drain() {
            let _ = tx.send(Err(NetError::Network("the node stopped".into())));
        }
    }

    fn periodic(&mut self) {
        if let Some(n) = &self.cfg.names_server {
            n.0.prune(crate::now_ms());
        }
        let k = &mut self.swarm.behaviour_mut().kad;
        // With an empty routing table there is no one to bootstrap from; asking
        // anyway only makes libp2p warn "No known peers" every tick.
        if routing_empty(k) {
            return;
        }
        if k.bootstrap().is_ok() {
            k.get_providers(kad::RecordKey::new(&self.profile.relay_key));
            if self.cfg.relay_server {
                let _ = k.start_providing(kad::RecordKey::new(&self.profile.relay_key));
            }
        }
    }

    fn add_relay(&mut self, addr: Multiaddr) {
        let Some(peer) = addr_peer(&addr) else {
            tracing::warn!("network: relay address {addr} has no /p2p/ peer id");
            return;
        };
        if peer == *self.swarm.local_peer_id() || !self.relay_listening.insert(peer) {
            return;
        }
        self.relays.insert(peer);
        self.swarm.add_peer_address(peer, addr.clone());
        let circuit = addr.with(Protocol::P2pCircuit);
        match self.swarm.listen_on(circuit.clone()) {
            Ok(id) => {
                self.relay_listeners.insert(peer, (circuit, id, std::time::Instant::now()));
            }
            Err(e) => {
                tracing::warn!("network: cannot listen through relay {circuit}: {e}");
                self.relay_listening.remove(&peer);
            }
        }
    }

    /// A reservation asked for while another dial to the relay was under way is never sent
    /// (libp2p's relay client skips its own dial then); once connected, ask again.
    fn retry_stuck_reservations(&mut self) {
        let reserved = self.status.lock().map(|s| s.reservations.clone()).unwrap_or_default();
        let stuck: Vec<PeerId> = self
            .relay_listeners
            .iter()
            .filter(|(p, (_, _, at))| at.elapsed() > Duration::from_secs(3) && !reserved.contains(&p.to_string()) && self.swarm.is_connected(p))
            .map(|(p, _)| *p)
            .collect();
        for p in stuck {
            if let Some((circuit, id, _)) = self.relay_listeners.remove(&p) {
                tracing::debug!("network: asking relay {p} for a reservation again");
                self.swarm.remove_listener(id);
                match self.swarm.listen_on(circuit.clone()) {
                    Ok(id) => {
                        self.relay_listeners.insert(p, (circuit, id, std::time::Instant::now()));
                    }
                    Err(e) => tracing::warn!("network: cannot listen through relay {circuit}: {e}"),
                }
            }
        }
    }

    fn command(&mut self, c: Cmd<Q, R>) {
        match c {
            Cmd::Request { peer, addrs, wire, reply } => {
                for a in addrs {
                    self.swarm.add_peer_address(peer, a);
                }
                let id = self.swarm.behaviour_mut().rr.send_request(&peer, wire);
                self.pending.insert(id, reply);
            }
            Cmd::Names { peer, addrs, req, reply } => {
                for a in addrs {
                    self.swarm.add_peer_address(peer, a);
                }
                let id = self.swarm.behaviour_mut().names.send_request(&peer, req);
                self.names_pending.insert(id, reply);
            }
            Cmd::PutEntry { entry, reply } => {
                let key = kad::RecordKey::new(&self.profile.record_key(entry.user_id()));
                let existing = self.swarm.behaviour_mut().kad.store_mut().get(&key).and_then(|r| Entry::decode(&r.value).ok());
                if let Err(e) = self.profile.accept(existing.as_ref(), &entry, crate::now_ms()) {
                    let _ = reply.send(Err(e));
                    return;
                }
                let rec = record_of(key, &entry);
                match self.swarm.behaviour_mut().kad.put_record(rec, kad::Quorum::One) {
                    Ok(q) => {
                        self.puts.insert(q, reply);
                    }
                    Err(e) => {
                        let _ = reply.send(Err(net_err(e)));
                    }
                }
            }
            Cmd::GetEntries { user, reply } => {
                let q = self.swarm.behaviour_mut().kad.get_record(kad::RecordKey::new(&self.profile.record_key(&user)));
                self.gets.insert(q, (vec![], reply));
            }
            Cmd::FindPeer { peer, reply } => {
                let q = self.swarm.behaviour_mut().kad.get_closest_peers(peer);
                self.finds.insert(q, (peer, reply));
            }
            Cmd::KnownAddrs { reply } => {
                let v = self.addr_book.iter().flat_map(|(p, a)| a.iter().map(|a| (*p, a.clone()))).collect();
                let _ = reply.send(Ok(v));
            }
            Cmd::Dial { addr, reply } => {
                let peer = addr_peer(&addr);
                match self.swarm.dial(addr.clone()) {
                    Ok(()) => self.dials.push((addr, peer, reply)),
                    Err(e) => {
                        let _ = reply.send(Err(net_err(e)));
                    }
                }
            }
            Cmd::Listen { addr, reply } => match self.swarm.listen_on(addr) {
                Ok(id) => {
                    self.listens.insert(id, reply);
                }
                Err(e) => {
                    let _ = reply.send(Err(net_err(e)));
                }
            },
            Cmd::AddRelay { addr } => self.add_relay(addr),
            Cmd::Stop => {}
        }
    }

    fn event(&mut self, ev: SwarmEvent<BehaviourEvent<Q, R>>) {
        match ev {
            SwarmEvent::NewListenAddr { listener_id, address } => {
                tracing::info!("network: listening on {address}");
                // a relay announces where it listens: reservations carry those addresses
                if self.cfg.relay_server && self.cfg.external.is_empty() && routable(&address) && !address.iter().any(|p| p == Protocol::P2pCircuit) {
                    self.swarm.add_external_address(address.clone());
                }
                if let Some(tx) = self.listens.remove(&listener_id) {
                    let _ = tx.send(Ok(address));
                }
                self.refresh();
            }
            SwarmEvent::ListenerClosed { listener_id, .. } => {
                if let Some(tx) = self.listens.remove(&listener_id) {
                    let _ = tx.send(Err(NetError::Network("listener closed".into())));
                }
                self.refresh();
            }
            SwarmEvent::ExternalAddrConfirmed { address } => {
                // a relay keeps to its configured addresses (or at least routable ones)
                if self.cfg.relay_server && (!routable(&address) || (!self.cfg.external.is_empty() && !self.cfg.external.contains(&address))) {
                    self.swarm.remove_external_address(&address);
                }
                self.refresh()
            }
            SwarmEvent::ExternalAddrExpired { .. } | SwarmEvent::ExpiredListenAddr { .. } => self.refresh(),
            SwarmEvent::ConnectionEstablished { peer_id, endpoint, .. } => {
                let addr = endpoint.get_remote_address().clone();
                if endpoint.is_dialer() {
                    let a = if addr_peer(&addr) == Some(peer_id) { addr.clone() } else { addr.clone().with(Protocol::P2p(peer_id)) };
                    let book = self.addr_book.entry(peer_id).or_default();
                    if !book.contains(&a) {
                        book.push(a);
                    }
                }
                let mut i = 0;
                while i < self.dials.len() {
                    let (a, p, _) = &self.dials[i];
                    if *a == addr || p.is_some_and(|p| p == peer_id) {
                        let (_, _, tx) = self.dials.remove(i);
                        let _ = tx.send(Ok(peer_id));
                    } else {
                        i += 1;
                    }
                }
                self.refresh();
            }
            SwarmEvent::ConnectionClosed { .. } => self.refresh(),
            SwarmEvent::OutgoingConnectionError { peer_id, error, .. } => {
                let msg = error.to_string();
                let mut i = 0;
                while i < self.dials.len() {
                    if peer_id.is_some() && self.dials[i].1 == peer_id {
                        let (_, _, tx) = self.dials.remove(i);
                        let _ = tx.send(Err(net_err(&msg)));
                    } else {
                        i += 1;
                    }
                }
                if peer_id.is_none() && !self.dials.is_empty() {
                    // an address without /p2p/: the oldest dial failed
                    let (_, _, tx) = self.dials.remove(0);
                    let _ = tx.send(Err(net_err(&msg)));
                }
            }
            SwarmEvent::Behaviour(b) => self.behaviour(b),
            _ => {}
        }
    }

    fn behaviour(&mut self, ev: BehaviourEvent<Q, R>) {
        match ev {
            BehaviourEvent::Rr(request_response::Event::Message { peer, message, .. }) => match message {
                request_response::Message::Request { request, channel, .. } => {
                    let h = self.handler.clone();
                    let tx = self.resp_tx.clone();
                    tokio::task::spawn_blocking(move || {
                        let resp = h.request(&peer, request);
                        let _ = tx.send((channel, resp));
                    });
                }
                request_response::Message::Response { request_id, response } => {
                    if let Some(tx) = self.pending.remove(&request_id) {
                        let _ = tx.send(Ok(response));
                    }
                }
            },
            BehaviourEvent::Rr(request_response::Event::OutboundFailure { request_id, error, peer, .. }) => {
                if let Some(tx) = self.pending.remove(&request_id) {
                    let _ = tx.send(Err(NetError::Network(format!("{} could not be reached ({error})", crate::short_peer_id(&peer)))));
                }
            }
            BehaviourEvent::Rr(request_response::Event::InboundFailure { peer, error, .. }) => {
                tracing::debug!("network: inbound request from {peer} failed: {error}");
            }
            BehaviourEvent::Names(request_response::Event::Message { peer, message, .. }) => match message {
                request_response::Message::Request { request, channel, .. } => {
                    let Some(store) = self.cfg.names_server.clone() else { return };
                    let tx = self.names_tx.clone();
                    let profile = self.profile;
                    tokio::task::spawn_blocking(move || {
                        let resp = crate::names::serve(profile, &*store.0, &peer, request, crate::now_ms());
                        let _ = tx.send((channel, resp));
                    });
                }
                request_response::Message::Response { request_id, response } => {
                    if let Some(tx) = self.names_pending.remove(&request_id) {
                        let _ = tx.send(Ok(response));
                    }
                }
            },
            BehaviourEvent::Names(request_response::Event::OutboundFailure { request_id, error, peer, .. }) => {
                if let Some(tx) = self.names_pending.remove(&request_id) {
                    let _ = tx.send(Err(NetError::Network(format!("names server {} could not be reached ({error})", crate::short_peer_id(&peer)))));
                }
            }
            BehaviourEvent::Kad(kad::Event::InboundRequest { request }) => match request {
                kad::InboundRequest::PutRecord { record: Some(rec), source, .. } => self.inbound_put(rec, source),
                kad::InboundRequest::AddProvider { record: Some(rec) } => {
                    // the only provider key nodes announce is the relay key
                    if rec.key.as_ref() == self.profile.relay_key.as_bytes() {
                        let _ = self.swarm.behaviour_mut().kad.store_mut().add_provider(rec);
                    }
                }
                _ => {}
            },
            BehaviourEvent::Kad(kad::Event::OutboundQueryProgressed { id, result: kad::QueryResult::PutRecord(r), .. }) => {
                if let Some(tx) = self.puts.remove(&id) {
                    let _ = tx.send(r.map(|_| ()).map_err(net_err));
                }
            }
            BehaviourEvent::Kad(kad::Event::OutboundQueryProgressed { id, result: kad::QueryResult::GetRecord(r), step, .. }) => {
                let done = match r {
                    Ok(kad::GetRecordOk::FoundRecord(pr)) => {
                        if let Some((v, _)) = self.gets.get_mut(&id)
                            && let Ok(e) = Entry::decode(&pr.record.value)
                        {
                            v.push(e);
                        }
                        step.last
                    }
                    _ => true,
                };
                if done && let Some((v, tx)) = self.gets.remove(&id) {
                    let _ = tx.send(Ok(v));
                    if let Some(mut q) = self.swarm.behaviour_mut().kad.query_mut(&id) {
                        q.finish();
                    }
                }
            }
            BehaviourEvent::Kad(kad::Event::OutboundQueryProgressed { id, result: kad::QueryResult::GetClosestPeers(r), .. }) => {
                if let Some((peer, tx)) = self.finds.remove(&id) {
                    let addrs = match r {
                        Ok(ok) => ok.peers,
                        Err(kad::GetClosestPeersError::Timeout { peers, .. }) => peers,
                    }
                    .into_iter()
                    .filter(|i| i.peer_id == peer)
                    .flat_map(|i| i.addrs)
                    .map(|a| if addr_peer(&a) == Some(peer) { a } else { a.with(Protocol::P2p(peer)) })
                    .collect();
                    let _ = tx.send(Ok(addrs));
                }
            }
            BehaviourEvent::Mdns(mdns::Event::Discovered(list)) => {
                let mut by_peer: HashMap<PeerId, Vec<Multiaddr>> = HashMap::new();
                for (p, a) in list {
                    by_peer.entry(p).or_default().push(a);
                }
                for (p, addrs) in by_peer {
                    for a in &addrs {
                        self.swarm.add_peer_address(p, a.clone());
                        self.swarm.behaviour_mut().kad.add_address(&p, a.clone());
                    }
                    if !self.swarm.is_connected(&p) {
                        let _ = self.swarm.dial(p);
                    }
                    self.seen(Sighting { peer: p, addrs: addrs.iter().map(|a| a.to_string()).collect(), caps: None, agent: None, source: "mdns" });
                }
            }
            BehaviourEvent::Identify(identify::Event::Received { peer_id, info, .. }) => {
                let protos: Vec<String> = info.protocols.iter().map(|p| p.to_string()).collect();
                let mut caps = vec![];
                if protos.iter().any(|p| p == self.profile.protocol) {
                    caps.push(self.profile.name.to_string());
                }
                if protos.iter().any(|p| *p == relay::HOP_PROTOCOL_NAME.to_string()) {
                    caps.push("relay".to_string());
                }
                if protos.iter().any(|p| p == self.profile.kad) {
                    caps.push("kad".to_string());
                    for a in &info.listen_addrs {
                        self.swarm.behaviour_mut().kad.add_address(&peer_id, a.clone());
                    }
                }
                let is_relay = caps.iter().any(|c| c == "relay");
                let addrs: Vec<String> = info.listen_addrs.iter().filter(|a| shareable(a)).map(|a| a.to_string()).collect();
                self.seen(Sighting { peer: peer_id, addrs, caps: Some(caps), agent: Some(info.agent_version), source: "identify" });
                // behind NAT: use relays we meet
                let private = self.status.lock().map(|s| s.nat == "private").unwrap_or(false);
                if is_relay
                    && private
                    && self.relay_listening.is_empty()
                    && let Some(a) = info.listen_addrs.iter().filter(|a| shareable(a)).min_by_key(|a| reach_rank(a))
                {
                    self.add_relay(a.clone().with(Protocol::P2p(peer_id)));
                }
            }
            BehaviourEvent::Kad(kad::Event::OutboundQueryProgressed {
                result: kad::QueryResult::GetProviders(Ok(kad::GetProvidersOk::FoundProviders { providers, .. })),
                ..
            }) => {
                for p in providers {
                    if p != *self.swarm.local_peer_id() {
                        self.seen(Sighting { peer: p, addrs: vec![], caps: Some(vec!["relay".into(), "kad".into()]), agent: None, source: "kad" });
                    }
                }
            }
            BehaviourEvent::Autonat(autonat::Event::StatusChanged { new, .. }) => {
                let nat = match new {
                    autonat::NatStatus::Public(_) => "public",
                    autonat::NatStatus::Private => "private",
                    autonat::NatStatus::Unknown => "unknown",
                };
                self.update(|s| s.nat = nat.into());
                if nat == "private" {
                    let relays: Vec<PeerId> = self.relays.iter().copied().collect();
                    tracing::info!("network: behind NAT; {} relay(s) known", relays.len());
                }
            }
            BehaviourEvent::RelayClient(relay::client::Event::ReservationReqAccepted { relay_peer_id, .. }) => {
                tracing::info!("network: reservation on relay {relay_peer_id}");
                self.update(|s| {
                    let r = relay_peer_id.to_string();
                    if !s.reservations.contains(&r) {
                        s.reservations.push(r);
                    }
                });
            }
            BehaviourEvent::Dcutr(e) => {
                tracing::debug!("network: hole punch with {}: {}", e.remote_peer_id, if e.result.is_ok() { "direct" } else { "failed" });
            }
            _ => {}
        }
    }
}

/// A Kademlia record holding a names entry, expiring with it.
fn record_of(key: kad::RecordKey, entry: &Entry) -> kad::Record {
    let mut rec = kad::Record::new(key, entry.encode());
    let left = (entry.expires() - crate::now_ms()).max(0) as u64;
    rec.expires = Some(std::time::Instant::now() + Duration::from_millis(left));
    rec
}

impl<Q: Message, R: Message> Loop<Q, R> {
    /// A peer put a record: keep it only if it is a valid names entry under its own key
    /// that supersedes what we hold (see [`Profile::accept`]).
    fn inbound_put(&mut self, rec: kad::Record, source: PeerId) {
        let Ok(entry) = Entry::decode(&rec.value) else {
            tracing::debug!("network: refused a DHT record from {source}: not a names entry");
            return;
        };
        let key = kad::RecordKey::new(&self.profile.record_key(entry.user_id()));
        if rec.key != key {
            tracing::debug!("network: refused a DHT record from {source}: wrong key");
            return;
        }
        let store = self.swarm.behaviour_mut().kad.store_mut();
        let existing = store.get(&key).and_then(|r| Entry::decode(&r.value).ok());
        match self.profile.accept(existing.as_ref(), &entry, crate::now_ms()) {
            Ok(()) => {
                let mut r = record_of(key, &entry);
                r.publisher = rec.publisher;
                let _ = store.put(r);
            }
            Err(e) => tracing::debug!("network: refused a DHT record from {source}: {e}"),
        }
    }
}

/// True when the Kademlia routing table holds no peers yet.
fn routing_empty<S: kad::store::RecordStore + Send + 'static>(k: &mut kad::Behaviour<S>) -> bool {
    k.kbuckets().all(|b| b.num_entries() == 0)
}