Skip to main content

zebra_network/peer_set/
initialize.rs

1//! A peer set whose size is dynamically determined by resource constraints.
2//!
3//! The [`PeerSet`] implementation is adapted from the one in [tower::Balance][tower-balance].
4//!
5//! [tower-balance]: https://github.com/tower-rs/tower/tree/master/tower/src/balance
6
7use std::{
8    collections::{BTreeMap, HashMap, HashSet},
9    convert::Infallible,
10    net::{IpAddr, SocketAddr},
11    sync::Arc,
12    time::Duration,
13};
14
15use futures::{future::FutureExt, sink::SinkExt, stream::StreamExt, TryFutureExt};
16use rand::seq::SliceRandom;
17use tokio::{
18    net::{TcpListener, TcpStream},
19    sync::{broadcast, mpsc, watch},
20    task::JoinSet,
21    time::{sleep, Instant},
22};
23use tokio_stream::wrappers::IntervalStream;
24use tower::{discover::Change, layer::Layer, Service, ServiceExt};
25use tracing::Instrument;
26
27use zebra_chain::{
28    chain_tip::ChainTip,
29    diagnostic::task::{CheckForPanics, WaitForPanics},
30    parameters::Network,
31};
32
33use crate::{
34    address_book_updater::{
35        AddressBookChangeSender, AddressBookRequest, AddressBookService, AddressBookUpdater,
36        MIN_CHANNEL_SIZE,
37    },
38    connection_metrics::{
39        network_kind_label, record_connection_attempt_finished, record_connection_attempt_started,
40        record_inbound_connection_rejected, ConnectionDirection,
41    },
42    constants,
43    meta_addr::MetaAddr,
44    peer::{
45        self, address_is_valid_for_inbound_listeners, HandshakeRequest, MinimumPeerVersion,
46        OutboundConnectorRequest, PeerPreference,
47    },
48    peer_cache_updater::peer_cache_updater,
49    peer_set::{
50        crawl_once, crawler_services, next_reconnect_peer, ready_peer_count, set::MorePeers,
51        ActiveConnectionCounter, ConnectionTracker, CrawlService, NextPeerService, PeerSet,
52    },
53    protocol::external::{canonical_peer_addr, canonical_socket_addr},
54    AddressBook, BanList, BoxError, Config, MisbehaviorReport, NetworkService, PeerSocketAddr,
55    Request, Response,
56};
57
58#[cfg(test)]
59mod tests;
60
61mod recent_by_ip;
62
63/// A successful outbound peer connection attempt or inbound connection handshake.
64///
65/// The [`Handshake`](peer::Handshake) service returns a [`Result`]. Only successful connections
66/// should be sent on the channel. Errors should be logged or ignored.
67///
68/// We don't allow any errors in this type, because:
69/// - The connection limits don't include failed connections
70/// - tower::Discover interprets an error as stream termination
71type DiscoveredPeer = (PeerSocketAddr, peer::Client);
72
73/// Initialize a peer set, using a network `config`, `inbound_service`,
74/// and `latest_chain_tip`.
75///
76/// The peer set abstracts away peer management to provide a
77/// [`tower::Service`] representing "the network" that load-balances requests
78/// over available peers.  The peer set automatically crawls the network to
79/// find more peer addresses and opportunistically connects to new peers.
80///
81/// Each peer connection's message handling is isolated from other
82/// connections, unlike in `zcashd`.  The peer connection first attempts to
83/// interpret inbound messages as part of a response to a previously-issued
84/// request.  Otherwise, inbound messages are interpreted as requests and sent
85/// to the supplied `inbound_service`.
86///
87/// Wrapping the `inbound_service` in [`tower::load_shed`] middleware will
88/// cause the peer set to shrink when the inbound service is unable to keep up
89/// with the volume of inbound requests.
90///
91/// Releasing the last [`NetworkService`] handle and unfinished response stops the network's
92/// background tasks and releases its listener and peer connections. Internal polling and
93/// crawling do not keep the network alive.
94/// Services retained by `inbound_service` must use [`NetworkService::background_service`]
95/// rather than retain an owning network handle.
96///
97/// Use [`NoChainTip`][1] to explicitly provide no chain tip receiver.
98///
99/// In addition to returning a service for outbound requests, this method
100/// returns a shared [`AddressBook`] updated with last-seen timestamps for
101/// connected peers. The shared address book should be accessed using a
102/// [blocking thread](https://docs.rs/tokio/1.15.0/tokio/task/index.html#blocking-and-yielding),
103/// to avoid async task deadlocks.
104///
105/// The fourth result is an independently bounded [`crate::BlockAdvertiser`]. Outbound block
106/// adverts must use it, not the ordinary buffered service. Its success acknowledges completed
107/// local transport writes to selected peers; admission alone and zero-peer fanout are not success.
108/// Readiness waits for an eligible connected peer, independently of ordinary request readiness.
109///
110/// # Panics
111///
112/// If `config.config.peerset_initial_target_size` is zero.
113/// (zebra-network expects to be able to connect to at least one peer.)
114///
115/// [1]: zebra_chain::chain_tip::NoChainTip
116pub async fn init<S, C>(
117    config: Config,
118    inbound_service: S,
119    latest_chain_tip: C,
120    user_agent: String,
121) -> (
122    NetworkService,
123    Arc<std::sync::Mutex<AddressBook>>,
124    mpsc::Sender<MisbehaviorReport>,
125    super::BlockAdvertiser<C>,
126)
127where
128    S: Service<Request, Response = Response, Error = BoxError> + Clone + Send + Sync + 'static,
129    S::Future: Send + 'static,
130    C: ChainTip + Clone + Send + Sync + 'static,
131{
132    init_with_block_gossip_peer_ips(
133        config,
134        inbound_service,
135        latest_chain_tip,
136        user_agent,
137        Vec::new(),
138    )
139    .await
140}
141
142/// Initialize a peer set like [`init`], additionally pinning block inventory
143/// broadcasts to the inbound peers at `block_gossip_peer_ips`.
144///
145/// Inbound peers connecting from these IP addresses always receive block
146/// inventory broadcasts, and one inbound connection slot is reserved for them.
147/// This is used by zcashd-compat mode, where a zcashd wallet sidecar makes a
148/// single P2P connection to this node and must reliably learn about new blocks.
149pub async fn init_with_block_gossip_peer_ips<S, C>(
150    config: Config,
151    inbound_service: S,
152    latest_chain_tip: C,
153    user_agent: String,
154    block_gossip_peer_ips: Vec<IpAddr>,
155) -> (
156    NetworkService,
157    Arc<std::sync::Mutex<AddressBook>>,
158    mpsc::Sender<MisbehaviorReport>,
159    super::BlockAdvertiser<C>,
160)
161where
162    S: Service<Request, Response = Response, Error = BoxError> + Clone + Send + Sync + 'static,
163    S::Future: Send + 'static,
164    C: ChainTip + Clone + Send + Sync + 'static,
165{
166    let (tcp_listener, listen_addr) = open_listener(&config.clone()).await;
167
168    let (
169        address_book,
170        bans_receiver,
171        address_book_updater,
172        address_book_service,
173        address_metrics,
174        address_book_updater_guard,
175    ) = AddressBookUpdater::spawn(&config, listen_addr);
176
177    let (misbehavior_tx, misbehavior_rx) = mpsc::channel::<MisbehaviorReport>(
178        // Leave enough room for a misbehaviour update on every peer connection
179        // before the channel is drained.
180        config
181            .peerset_total_connection_limit()
182            .max(MIN_CHANNEL_SIZE),
183    );
184
185    let misbehavior_guard = tokio::spawn(
186        batch_misbehavior_updates(
187            misbehavior_rx,
188            address_book_updater.clone(),
189            constants::MISBEHAVIOR_FLUSH_INTERVAL,
190        )
191        .in_current_span(),
192    );
193
194    // Create a broadcast channel for peer inventory advertisements.
195    // If it reaches capacity, this channel drops older inventory advertisements.
196    //
197    // When Zebra is at the chain tip with an up-to-date mempool,
198    // we expect to have at most 1 new transaction per connected peer,
199    // and 1-2 new blocks across the entire network.
200    // (The block syncer and mempool crawler handle bulk fetches of blocks and transactions.)
201    let (inv_sender, inv_receiver) = broadcast::channel(config.peerset_total_connection_limit());
202
203    // Construct services that handle inbound handshakes and perform outbound
204    // handshakes. These use the same handshake service internally to detect
205    // self-connection attempts. Both are decorated with a tower TimeoutLayer to
206    // enforce timeouts as specified in the Config.
207    let (listen_handshaker, outbound_connector) = {
208        use tower::timeout::TimeoutLayer;
209        let hs_timeout = TimeoutLayer::new(constants::HANDSHAKE_TIMEOUT);
210        use crate::protocol::external::types::PeerServices;
211        let hs = peer::Handshake::builder()
212            .with_config(config.clone())
213            .with_inbound_service(inbound_service)
214            .with_inventory_collector(inv_sender)
215            .with_address_book_updater(address_book_updater.clone())
216            .with_bans(bans_receiver.clone())
217            .with_advertised_services(PeerServices::NODE_NETWORK)
218            .with_user_agent(user_agent)
219            .with_latest_chain_tip(latest_chain_tip.clone())
220            .want_transactions(true)
221            .finish()
222            .expect("configured all required parameters");
223        (
224            hs_timeout.layer(hs.clone()),
225            hs_timeout.layer(peer::Connector::new(hs)),
226        )
227    };
228
229    // Create an mpsc channel for peer changes,
230    // based on the maximum number of inbound and outbound peers.
231    //
232    // The connection limit does not apply to errors,
233    // so they need to be handled before sending to this channel.
234    let (peerset_tx, peerset_rx) =
235        futures::channel::mpsc::channel::<DiscoveredPeer>(config.peerset_total_connection_limit());
236
237    let discovered_peers = peerset_rx.map(|(address, client)| {
238        Result::<_, Infallible>::Ok(Change::Insert(address, client.into()))
239    });
240
241    // Create an mpsc channel for peerset demand signaling,
242    // based on the maximum number of outbound peers.
243    let (mut demand_tx, demand_rx) =
244        futures::channel::mpsc::channel::<MorePeers>(config.peerset_outbound_connection_limit());
245
246    // Create a oneshot to send background task JoinHandles to the peer set
247    let (handle_tx, handle_rx) = tokio::sync::oneshot::channel();
248
249    // Connect the rx end to a PeerSet, wrapping new peers in load instruments.
250    let peer_set = PeerSet::new(
251        &config,
252        block_gossip_peer_ips.clone(),
253        discovered_peers,
254        demand_tx.clone(),
255        handle_rx,
256        inv_receiver,
257        bans_receiver.clone(),
258        address_metrics,
259        MinimumPeerVersion::new(latest_chain_tip, &config.network),
260        None,
261    );
262    // Also route queued peer set requests as soon as a peer that might serve them is ready.
263    let block_advertiser = peer_set.block_advertiser();
264    let (mut peer_set, poll_peer_set_guard) = peer_set.into_buffer(constants::PEERSET_BUFFER_SIZE);
265    peer_set.extend_tasks([
266        address_book_updater_guard.abort_handle(),
267        misbehavior_guard.abort_handle(),
268    ]);
269
270    // Connect peerset_tx to the 3 peer sources:
271    //
272    // 1. Incoming peer connections, via a listener.
273    let listen_fut = accept_inbound_connections(
274        config.clone(),
275        tcp_listener,
276        constants::MIN_INBOUND_PEER_CONNECTION_INTERVAL,
277        listen_handshaker,
278        peerset_tx.clone(),
279        bans_receiver,
280        block_gossip_peer_ips,
281    );
282    let listen_guard = tokio::spawn(listen_fut.in_current_span());
283    peer_set.extend_tasks([listen_guard.abort_handle()]);
284
285    // 2. Initial peers, specified in the config and cached on disk.
286    let initial_peers_fut = add_initial_peers(
287        config.clone(),
288        outbound_connector.clone(),
289        peerset_tx.clone(),
290        address_book_service.clone(),
291    );
292    let initial_peers_join = tokio::spawn(initial_peers_fut.in_current_span());
293    peer_set.extend_tasks([initial_peers_join.abort_handle()]);
294
295    // 3. Outgoing peers we connect to in response to load.
296    let (next_peer_service, mut crawl_service) =
297        crawler_services(address_book_service.clone(), peer_set.background_service());
298
299    // Wait for the initial seed peer count
300    let mut active_outbound_connections = initial_peers_join
301        .wait_for_panics()
302        .await
303        .expect("unexpected error connecting to initial peers");
304    let active_initial_peer_count = active_outbound_connections.update_count();
305
306    // We need to await the initial crawl here,
307    // because zcashd rate-limits `addr`/`addrv2` messages per connection,
308    // and if we only have one initial peer,
309    // we need to ensure that its `Response::Addr` is used by the crawler.
310    //
311    // TODO: this might not be needed after we added the Connection peer address cache,
312    //       try removing it in a future release?
313    info!(
314        ?active_initial_peer_count,
315        "sending initial request for peers"
316    );
317    let _ = crawl_once(&mut crawl_service, Some(active_initial_peer_count)).await;
318
319    // Compute remaining connections to open.
320    let demand_count = config
321        .peerset_initial_target_size
322        .saturating_sub(active_outbound_connections.update_count());
323
324    for _ in 0..demand_count {
325        let _ = demand_tx.try_send(MorePeers);
326    }
327
328    // Start the peer crawler
329    let crawl_fut = crawl_and_dial(
330        config.clone(),
331        demand_tx,
332        demand_rx,
333        next_peer_service,
334        crawl_service,
335        address_book_service.clone(),
336        outbound_connector,
337        peerset_tx,
338        active_outbound_connections,
339        address_book_updater,
340    );
341    let crawl_guard = tokio::spawn(crawl_fut.in_current_span());
342    peer_set.extend_tasks([crawl_guard.abort_handle()]);
343
344    // Start the peer disk cache updater
345    let peer_cache_updater_fut = peer_cache_updater(config, address_book_service);
346    let peer_cache_updater_guard = tokio::spawn(peer_cache_updater_fut.in_current_span());
347    peer_set.extend_tasks([peer_cache_updater_guard.abort_handle()]);
348
349    handle_tx
350        .send(vec![
351            listen_guard,
352            crawl_guard,
353            address_book_updater_guard,
354            peer_cache_updater_guard,
355            poll_peer_set_guard,
356        ])
357        .unwrap();
358
359    (peer_set, address_book, misbehavior_tx, block_advertiser)
360}
361
362/// Use the provided `outbound_connector` to connect to the configured DNS seeder and
363/// disk cache initial peers, then send the resulting peer connections over `peerset_tx`.
364///
365/// Also adds every initial peer address to the address book.
366#[instrument(skip(config, outbound_connector, peerset_tx, address_book_service))]
367async fn add_initial_peers<S>(
368    config: Config,
369    outbound_connector: S,
370    mut peerset_tx: futures::channel::mpsc::Sender<DiscoveredPeer>,
371    address_book_service: AddressBookService,
372) -> Result<ActiveConnectionCounter, BoxError>
373where
374    S: Service<
375            OutboundConnectorRequest,
376            Response = (PeerSocketAddr, peer::Client),
377            Error = BoxError,
378        > + Clone
379        + Send
380        + 'static,
381    S::Future: Send + 'static,
382{
383    let initial_peers = limit_initial_peers(&config, &address_book_service).await;
384
385    let mut handshake_success_total: usize = 0;
386    let mut handshake_error_total: usize = 0;
387
388    let mut active_outbound_connections = ActiveConnectionCounter::new_counter_with(
389        config.peerset_outbound_connection_limit(),
390        "Outbound Connections",
391    );
392
393    // TODO: update when we add Tor peers or other kinds of addresses.
394    let ipv4_peer_count = initial_peers.iter().filter(|ip| ip.is_ipv4()).count();
395    let ipv6_peer_count = initial_peers.iter().filter(|ip| ip.is_ipv6()).count();
396    info!(
397        ?ipv4_peer_count,
398        ?ipv6_peer_count,
399        "connecting to initial peer set"
400    );
401
402    // # Security
403    //
404    // Resists distributed denial of service attacks by making sure that
405    // new peer connections are initiated at least `MIN_OUTBOUND_PEER_CONNECTION_INTERVAL` apart.
406    //
407    // Seed attempts belong to this task, including when initialization is cancelled.
408    let network = config.network.clone();
409    let mut handshakes = JoinSet::new();
410    for (i, addr) in initial_peers.into_iter().enumerate() {
411        let connection_tracker = active_outbound_connections.track_connection();
412        let req = OutboundConnectorRequest {
413            addr,
414            connection_tracker,
415        };
416        let outbound_connector = outbound_connector.clone();
417        let network = network.clone();
418
419        // Spawn a new task to make the outbound connection.
420        handshakes.spawn(
421            async move {
422                // Only spawn one outbound connector per
423                // `MIN_OUTBOUND_PEER_CONNECTION_INTERVAL`,
424                // by sleeping for the interval multiplied by the peer's index in the list.
425                sleep(constants::MIN_OUTBOUND_PEER_CONNECTION_INTERVAL.saturating_mul(i as u32))
426                    .await;
427
428                // As soon as we create the connector future,
429                // the handshake starts running as a spawned task.
430                record_connection_attempt_started(&network, ConnectionDirection::Outbound, addr);
431                let result = outbound_connector
432                    .oneshot(req)
433                    .map_err(move |e| (addr, e))
434                    .await;
435                record_connection_attempt_finished(
436                    &network,
437                    ConnectionDirection::Outbound,
438                    addr,
439                    result.as_ref().err().map(|(_, error)| error),
440                );
441                result
442            }
443            .in_current_span(),
444        );
445    }
446
447    while let Some(handshake_result) = handshakes.join_next().await {
448        let Ok(handshake_result) = handshake_result.panic_if_task_has_panicked() else {
449            continue;
450        };
451        match handshake_result {
452            Ok(change) => {
453                handshake_success_total += 1;
454                debug!(
455                    ?handshake_success_total,
456                    ?handshake_error_total,
457                    ?change,
458                    "an initial peer handshake succeeded"
459                );
460
461                // The connection limit makes sure this send doesn't block
462                peerset_tx.send(change).await?;
463            }
464            Err((addr, ref e)) => {
465                handshake_error_total += 1;
466
467                // this is verbose, but it's better than just hanging with no output when there are errors
468                let mut expected_error = false;
469                if let Some(io_error) = e.downcast_ref::<tokio::io::Error>() {
470                    // Some systems only have IPv4, or only have IPv6,
471                    // so these errors are not particularly interesting.
472                    if io_error.kind() == tokio::io::ErrorKind::AddrNotAvailable {
473                        expected_error = true;
474                    }
475                }
476
477                if expected_error {
478                    debug!(
479                        successes = ?handshake_success_total,
480                        errors = ?handshake_error_total,
481                        ?addr,
482                        ?e,
483                        "an initial peer connection failed"
484                    );
485                } else {
486                    info!(
487                        successes = ?handshake_success_total,
488                        errors = ?handshake_error_total,
489                        ?addr,
490                        %e,
491                        "an initial peer connection failed"
492                    );
493                }
494            }
495        }
496
497        // Security: Let other tasks run after each connection is processed.
498        //
499        // Avoids remote peers starving other Zebra tasks using initial connection successes or errors.
500        tokio::task::yield_now().await;
501    }
502
503    let outbound_connections = active_outbound_connections.update_count();
504    info!(
505        ?handshake_success_total,
506        ?handshake_error_total,
507        ?outbound_connections,
508        "finished connecting to initial seed and disk cache peers"
509    );
510
511    Ok(active_outbound_connections)
512}
513
514/// Limit the number of `initial_peers` addresses entries to the configured
515/// `peerset_initial_target_size`.
516///
517/// Returns randomly chosen entries from the provided set of addresses,
518/// in a random order.
519///
520/// Also adds every initial peer to the address book, before returning.
521async fn limit_initial_peers(
522    config: &Config,
523    address_book_service: &AddressBookService,
524) -> HashSet<PeerSocketAddr> {
525    let all_peers: HashSet<PeerSocketAddr> = config.initial_peers().await;
526    let mut preferred_peers: BTreeMap<PeerPreference, Vec<PeerSocketAddr>> = BTreeMap::new();
527
528    let all_peers_count = all_peers.len();
529    if all_peers_count > config.peerset_initial_target_size {
530        info!(
531            "limiting the initial peers list from {} to {}",
532            all_peers_count, config.peerset_initial_target_size,
533        );
534    }
535
536    // Filter out invalid initial peers, and prioritise valid peers for initial connections.
537    // (This treats initial peers the same way we treat gossiped peers.)
538    for peer_addr in all_peers {
539        let preference = PeerPreference::new(peer_addr, config.network.clone());
540
541        match preference {
542            Ok(preference) => preferred_peers
543                .entry(preference)
544                .or_default()
545                .push(peer_addr),
546            Err(error) => info!(
547                ?peer_addr,
548                ?error,
549                "invalid initial peer from DNS seeder, configured IP address, or disk cache",
550            ),
551        }
552    }
553
554    // Send every initial peer to the address book, in preferred order.
555    // (This treats initial peers the same way we treat gossiped peers.)
556    //
557    // # Security
558    //
559    // Initial peers are limited because:
560    // - the number of initial peers is limited
561    // - this code runs at startup, then at most once every
562    //   `MIN_INITIAL_PEER_RECOVERY_INTERVAL` while the node has no outbound peers
563    //
564    // # Correctness
565    //
566    // Add peers through the address book service, rather than the change channel,
567    // so later service requests, like the crawler's ready peer count, see them.
568    for peer in preferred_peers.values().flatten() {
569        // The address book serves each request without waiting, so this is quick.
570        let added = address_book_service
571            .clone()
572            .oneshot(AddressBookRequest::Change(MetaAddr::new_initial_peer(
573                *peer,
574            )))
575            .boxed()
576            .await;
577        if let Err(error) = added {
578            debug!(?error, "error adding initial peer, is Zebra shutting down?");
579            break;
580        }
581    }
582
583    // Split out the `initial_peers` that will be shuffled and returned,
584    // choosing preferred peers first.
585    let mut initial_peers: HashSet<PeerSocketAddr> = HashSet::new();
586    for better_peers in preferred_peers.values() {
587        let mut better_peers = better_peers.clone();
588        let (chosen_peers, _unused_peers) = better_peers.partial_shuffle(
589            &mut rand::rng(),
590            config.peerset_initial_target_size - initial_peers.len(),
591        );
592
593        initial_peers.extend(chosen_peers.iter());
594
595        if initial_peers.len() >= config.peerset_initial_target_size {
596            break;
597        }
598    }
599
600    initial_peers
601}
602
603/// Batches peer misbehaviour reports from `misbehavior_rx`, and sends them to the address
604/// book every `flush_interval`.
605///
606/// Batching stops peers from keeping the address book mutex locked by repeatedly sending
607/// invalid blocks or transactions.
608///
609/// Senders use `try_send()`, so this task keeps receiving while a flush is waiting for the
610/// address book updater. Otherwise the channel could fill up during the flush, and new
611/// reports would be dropped.
612///
613/// # Security
614///
615/// A report that bans a peer is sent right away, not at the next flush. A peer that serves a
616/// forged body for a block that only it advertised would otherwise keep getting the requests for
617/// that block until its ban landed, and the requester gives up after a few retries
618/// (GHSA-g9rc-89v4-hhvf). Each peer address gets at most one early ban per `flush_interval`, and
619/// banned peers are disconnected, so peers still can't keep the address book busy.
620async fn batch_misbehavior_updates(
621    mut misbehavior_rx: mpsc::Receiver<MisbehaviorReport>,
622    address_book_updater: AddressBookChangeSender,
623    flush_interval: Duration,
624) {
625    let mut batch = MisbehaviorBatch::default();
626    let mut flush_timer = IntervalStream::new(tokio::time::interval(flush_interval));
627
628    loop {
629        tokio::select! {
630            msg = misbehavior_rx.recv() => match msg {
631                Some(report) => batch.add(report),
632                None => break,
633            },
634
635            _ = flush_timer.next() => {
636                for (_, report) in batch.start_interval() {
637                    send_misbehavior_update(
638                        &address_book_updater,
639                        report,
640                        &mut batch,
641                        &mut misbehavior_rx,
642                    )
643                    .await;
644                }
645            },
646        };
647
648        while let Some(report) = batch.next_early_ban() {
649            send_misbehavior_update(
650                &address_book_updater,
651                report,
652                &mut batch,
653                &mut misbehavior_rx,
654            )
655            .await;
656        }
657    }
658
659    tracing::warn!("exiting misbehavior update batch task");
660}
661
662/// Sends `report` to the address book, and batches the reports received while the address book
663/// updater is busy, which are sent later.
664async fn send_misbehavior_update(
665    address_book_updater: &AddressBookChangeSender,
666    report: MisbehaviorReport,
667    batch: &mut MisbehaviorBatch,
668    misbehavior_rx: &mut mpsc::Receiver<MisbehaviorReport>,
669) {
670    let update = address_book_updater.send(MetaAddr::new_misbehavior(
671        report.addr,
672        report.score,
673        report.reason,
674    ));
675    tokio::pin!(update);
676
677    loop {
678        tokio::select! {
679            _ = &mut update => break,
680            Some(report) = misbehavior_rx.recv() => batch.add(report),
681        }
682    }
683}
684
685/// The misbehavior reports batched during a flush interval.
686#[derive(Debug, Default)]
687struct MisbehaviorBatch {
688    /// The batched reports, with the scores for the same peer summed.
689    reports: HashMap<PeerSocketAddr, MisbehaviorReport>,
690
691    /// The peers whose batched score reached the ban threshold during this flush interval.
692    /// Each of them gets one early ban.
693    early_bans: HashSet<PeerSocketAddr>,
694
695    /// The peers in `early_bans` whose ban hasn't been sent yet.
696    unsent_early_bans: Vec<PeerSocketAddr>,
697}
698
699impl MisbehaviorBatch {
700    /// Adds `report` to the batch, summing the scores for the same peer.
701    ///
702    /// Only the peer in `report` can reach the ban threshold, so this never scans the batch.
703    fn add(&mut self, report: MisbehaviorReport) {
704        let addr = report.addr;
705        // Keep the first reason: any report can cross the ban threshold.
706        let score = report.score;
707        let batched = self
708            .reports
709            .entry(addr)
710            .and_modify(|batched| batched.score = batched.score.saturating_add(score))
711            .or_insert(report);
712
713        if batched.score >= constants::MAX_PEER_MISBEHAVIOR_SCORE && self.early_bans.insert(addr) {
714            self.unsent_early_bans.push(addr);
715        }
716    }
717
718    /// Returns the batched report for a peer that reached the ban threshold, if its early ban
719    /// hasn't been sent yet.
720    fn next_early_ban(&mut self) -> Option<MisbehaviorReport> {
721        while let Some(addr) = self.unsent_early_bans.pop() {
722            if let Some(report) = self.reports.remove(&addr) {
723                return Some(report);
724            }
725        }
726
727        None
728    }
729
730    /// Starts a new flush interval, and returns the reports batched during the last one.
731    fn start_interval(&mut self) -> HashMap<PeerSocketAddr, MisbehaviorReport> {
732        self.early_bans.clear();
733        self.unsent_early_bans.clear();
734
735        std::mem::take(&mut self.reports)
736    }
737}
738
739/// Open a peer connection listener on `config.listen_addr`,
740/// returning the opened [`TcpListener`], and the address it is bound to.
741///
742/// If the listener is configured to use an automatically chosen port (port `0`),
743/// then the returned address will contain the actual port.
744///
745/// # Panics
746///
747/// If opening the listener fails.
748#[instrument(skip(config), fields(addr = ?config.listen_addr))]
749pub(crate) async fn open_listener(config: &Config) -> (TcpListener, SocketAddr) {
750    // Warn if we're configured using the wrong network port.
751    if let Err(wrong_addr) =
752        address_is_valid_for_inbound_listeners(config.listen_addr, config.network.clone())
753    {
754        warn!(
755            "We are configured with address {} on {:?}, but it could cause network issues. \
756             The default port for {:?} is {}. Error: {wrong_addr:?}",
757            config.listen_addr,
758            config.network,
759            config.network,
760            config.network.default_port(),
761        );
762    }
763
764    info!(
765        "Trying to open Zcash protocol endpoint at {}...",
766        config.listen_addr
767    );
768    let listener_result = TcpListener::bind(config.listen_addr).await;
769
770    let listener = match listener_result {
771        Ok(l) => l,
772        Err(e) => panic!(
773            "Opening Zcash network protocol listener {:?} failed: {e:?}. \
774             Hint: Check if another zebrad or zcashd process is running. \
775             Try changing the network listen_addr in the Zebra config.",
776            config.listen_addr,
777        ),
778    };
779
780    let local_addr = listener
781        .local_addr()
782        .expect("unexpected missing local addr for open listener");
783    info!("Opened Zcash protocol endpoint at {}", local_addr);
784
785    (listener, local_addr)
786}
787
788/// Listens for peer connections on `addr`, then sets up each connection as a
789/// Zcash peer.
790///
791/// Uses `handshaker` to perform a Zcash network protocol handshake, and sends
792/// the [`peer::Client`] result over `peerset_tx`.
793///
794/// Limits the number of active inbound connections based on `config`,
795/// and waits `min_inbound_peer_connection_interval` between connections.
796#[instrument(skip(config, listener, handshaker, peerset_tx), fields(listener_addr = ?listener.local_addr()))]
797async fn accept_inbound_connections<S>(
798    config: Config,
799    listener: TcpListener,
800    min_inbound_peer_connection_interval: Duration,
801    handshaker: S,
802    peerset_tx: futures::channel::mpsc::Sender<DiscoveredPeer>,
803    bans_receiver: watch::Receiver<BanList>,
804    zcashd_compat_peer_ips: Vec<IpAddr>,
805) -> Result<(), BoxError>
806where
807    S: Service<peer::HandshakeRequest<TcpStream>, Response = peer::Client, Error = BoxError>
808        + Clone,
809    S::Future: Send + 'static,
810{
811    let mut recent_inbound_connections =
812        recent_by_ip::RecentByIp::new(None, Some(config.max_connections_per_ip));
813
814    let mut active_inbound_connections = ActiveConnectionCounter::new_counter_with(
815        config.peerset_inbound_connection_limit(),
816        "Inbound Connections",
817    );
818    let zcashd_compat_peer_ips: HashSet<_> = zcashd_compat_peer_ips
819        .into_iter()
820        .map(|ip| canonical_socket_addr(SocketAddr::new(ip, 0)).ip())
821        .collect();
822    // Reserve one inbound slot per configured sidecar IP, always leaving at
823    // least one public slot. Reserved slots are a fast path, not a cap:
824    // when they are taken, further connections from listed IPs compete for
825    // public slots like any other peer, so an unrelated local process (or a
826    // sidecar reconnecting before its dead connection is noticed) can never
827    // lock the real sidecar out of the node.
828    let zcashd_compat_reserved_slots = zcashd_compat_peer_ips
829        .len()
830        .min(config.peerset_inbound_connection_limit().saturating_sub(1));
831    let mut active_zcashd_compat_connections = ActiveConnectionCounter::new_counter_with(
832        zcashd_compat_reserved_slots,
833        "zcashd-compat Inbound Connections",
834    );
835    let public_inbound_connection_limit = config
836        .peerset_inbound_connection_limit()
837        .saturating_sub(zcashd_compat_reserved_slots);
838
839    // Dropping the listener also aborts unfinished handshakes.
840    let mut handshakes = JoinSet::new();
841
842    loop {
843        // Check for panics in finished tasks, before accepting new connections
844        let inbound_result = tokio::select! {
845            biased;
846            next_handshake_res = handshakes.join_next(), if !handshakes.is_empty() => {
847                // The task has already sent the peer change to the peer set.
848                let _ = next_handshake_res
849                    .expect("the handshake set is not empty")
850                    .panic_if_task_has_panicked();
851                continue;
852            },
853
854            // This future must wait until new connections are available: it can't have a timeout.
855            inbound_result = listener.accept() => inbound_result,
856        };
857
858        if let Ok((tcp_stream, addr)) = inbound_result {
859            // # Security
860            //
861            // Canonicalize the accepted address before it is used as a key. On a
862            // dual-stack listener an IPv4 peer connects as IPv4-mapped IPv6, but
863            // bans and misbehaviour updates are keyed on the canonical IPv4 address.
864            // This address also becomes the peer set key and the per-IP limiter key
865            // below, so canonicalizing once here keeps all of them in the same form.
866            let addr: PeerSocketAddr = canonical_peer_addr(addr);
867            record_connection_attempt_started(&config.network, ConnectionDirection::Inbound, addr);
868
869            // # Security
870            //
871            // Bans are keyed by peer group, which unmaps IPv4-mapped IPv6 and
872            // masks IPv6 to its `/64`. So a peer cannot dodge a ban — and then
873            // be granted the zcashd-compat sidecar privileges below — by
874            // connecting as IPv4-mapped IPv6 on a dual-stack listener, or from
875            // another address in a banned `/64`.
876            let canonical_ip = canonical_socket_addr(addr.remove_socket_addr_privacy()).ip();
877            let bans = bans_receiver.borrow().clone();
878            if bans.is_banned(addr.ip()) {
879                debug!(?addr, "banned inbound connection attempt");
880                record_inbound_connection_rejected(&config.network, addr, "banned");
881                std::mem::drop(tcp_stream);
882                continue;
883            }
884
885            let active_public_inbound_connections = active_inbound_connections.update_count();
886            let active_zcashd_compat_inbound_connections =
887                active_zcashd_compat_connections.update_count();
888            let active_total_inbound_connections =
889                active_public_inbound_connections + active_zcashd_compat_inbound_connections;
890            let is_zcashd_compat_peer = zcashd_compat_peer_ips.contains(&canonical_ip);
891
892            // The peer already opened a connection to us.
893            // So we want to increment the connection count as soon as possible.
894            //
895            // Sidecar-listed IPs use a reserved slot when one is free, and
896            // otherwise fall back to competing for a public slot (including
897            // the recent-IP rate limit), so a taken reserved slot delays a
898            // sidecar rather than locking it out.
899            let use_reserved_slot = is_zcashd_compat_peer
900                && active_zcashd_compat_inbound_connections < zcashd_compat_reserved_slots
901                && active_total_inbound_connections < config.peerset_inbound_connection_limit();
902
903            let connection_tracker = if use_reserved_slot {
904                active_zcashd_compat_connections.track_connection()
905            } else if active_public_inbound_connections >= public_inbound_connection_limit
906                || active_total_inbound_connections >= config.peerset_inbound_connection_limit()
907                || recent_inbound_connections.is_past_limit_or_add(addr.ip())
908            {
909                // Too many open inbound connections or pending handshakes already.
910                // Close the connection.
911                record_inbound_connection_rejected(
912                    &config.network,
913                    addr,
914                    "capacity_or_rate_limited",
915                );
916                std::mem::drop(tcp_stream);
917                // Allow invalid connections to be cleared quickly,
918                // but still put a limit on our CPU and network usage from failed connections.
919                tokio::time::sleep(constants::MIN_INBOUND_PEER_FAILED_CONNECTION_INTERVAL).await;
920                continue;
921            } else {
922                active_inbound_connections.track_connection()
923            };
924            debug!(
925                inbound_connections = ?active_total_inbound_connections,
926                ?is_zcashd_compat_peer,
927                "handshaking on an open inbound peer connection"
928            );
929
930            accept_inbound_handshake(
931                config.network.clone(),
932                addr,
933                handshaker.clone(),
934                tcp_stream,
935                connection_tracker,
936                peerset_tx.clone(),
937                &mut handshakes,
938            )
939            .await?;
940
941            // Rate-limit inbound connection handshakes.
942            // But sleep longer after a successful connection,
943            // so we can clear out failed connections at a higher rate.
944            //
945            // If there is a flood of connections,
946            // this stops Zebra overloading the network with handshake data.
947            //
948            // Zebra can't control how many queued connections are waiting,
949            // but most OSes also limit the number of queued inbound connections on a listener port.
950            tokio::time::sleep(min_inbound_peer_connection_interval).await;
951        } else {
952            // Allow invalid connections to be cleared quickly,
953            // but still put a limit on our CPU and network usage from failed connections.
954            debug!(?inbound_result, "error accepting inbound connection");
955            tokio::time::sleep(constants::MIN_INBOUND_PEER_FAILED_CONNECTION_INTERVAL).await;
956        }
957
958        // Security: Let other tasks run after each connection is processed.
959        //
960        // Avoids remote peers starving other Zebra tasks using inbound connection successes or
961        // errors.
962        //
963        // Preventing a denial of service is important in this code, so we want to sleep *and* make
964        // the next connection after other tasks have run. (Sleeps are not guaranteed to do that.)
965        tokio::task::yield_now().await;
966    }
967}
968
969/// Set up a new inbound connection as a Zcash peer.
970///
971/// Uses `handshaker` to perform a Zcash network protocol handshake, and sends
972/// the [`peer::Client`] result over `peerset_tx`.
973//
974// TODO: when we support inbound proxies, distinguish between proxied listeners and
975//       direct listeners in the span generated by this instrument macro
976#[instrument(skip(handshaker, tcp_stream, connection_tracker, peerset_tx, handshakes))]
977async fn accept_inbound_handshake<S>(
978    network: Network,
979    addr: PeerSocketAddr,
980    mut handshaker: S,
981    tcp_stream: TcpStream,
982    connection_tracker: ConnectionTracker,
983    peerset_tx: futures::channel::mpsc::Sender<DiscoveredPeer>,
984    handshakes: &mut JoinSet<()>,
985) -> Result<(), BoxError>
986where
987    S: Service<peer::HandshakeRequest<TcpStream>, Response = peer::Client, Error = BoxError>
988        + Clone,
989    S::Future: Send + 'static,
990{
991    let connected_addr = peer::ConnectedAddr::new_inbound_direct(addr);
992
993    debug!("got incoming connection");
994
995    peer::set_tcp_nodelay(&tcp_stream);
996
997    // # Correctness
998    //
999    // Holding the drop guard returned by Span::enter across .await points will
1000    // result in incorrect traces if it yields.
1001    //
1002    // This await is okay because the handshaker's `poll_ready` method always returns Ready.
1003    handshaker.ready().await?;
1004
1005    // Construct a handshake future but do not drive it yet....
1006    let handshake = handshaker.call(HandshakeRequest {
1007        data_stream: tcp_stream,
1008        connected_addr,
1009        connection_tracker,
1010    });
1011    // ... instead, spawn a new task to handle this connection
1012    let mut peerset_tx = peerset_tx.clone();
1013
1014    handshakes.spawn(
1015        async move {
1016            let handshake_result = handshake.await;
1017            record_connection_attempt_finished(
1018                &network,
1019                ConnectionDirection::Inbound,
1020                addr,
1021                handshake_result.as_ref().err(),
1022            );
1023
1024            if let Ok(client) = handshake_result {
1025                // The connection limit makes sure this send doesn't block
1026                let _ = peerset_tx.send((addr, client)).await;
1027            } else {
1028                debug!(?handshake_result, "error handshaking with inbound peer");
1029            }
1030        }
1031        .in_current_span(),
1032    );
1033
1034    Ok(())
1035}
1036
1037/// An action that the peer crawler can take.
1038enum CrawlerAction {
1039    /// Drop the demand signal because there are too many pending handshakes.
1040    DemandDrop,
1041    /// Initiate a handshake to the next candidate peer in response to demand.
1042    ///
1043    /// If there are no available candidates, crawl existing peers.
1044    DemandHandshakeOrCrawl,
1045    /// Crawl existing peers for more peers, and queue dial attempts to fill
1046    /// any spare outbound connection capacity, in response to a timer `tick`.
1047    TimerCrawl { tick: Instant },
1048    /// Clear a finished handshake.
1049    HandshakeFinished,
1050    /// Clear a finished demand crawl (DemandHandshakeOrCrawl with no peers).
1051    DemandCrawlFinished,
1052    /// Clear a finished TimerCrawl, with `ready_candidates` candidates ready after crawling.
1053    TimerCrawlFinished { ready_candidates: usize },
1054    /// Clear a finished re-add of the initial peers, which left `ready_candidates`
1055    /// candidates ready to dial.
1056    InitialPeersReadded { ready_candidates: usize },
1057}
1058
1059/// Given a channel `demand_rx` that signals a need for new peers, try to find
1060/// and connect to new peers, and send the resulting `peer::Client`s through the
1061/// `peerset_tx` channel.
1062///
1063/// Crawl for new peers every `config.crawl_new_peer_interval`.
1064/// Also crawl whenever there is demand, but no new candidate peers.
1065/// After crawling, try to connect to one new peer using `outbound_connector`.
1066///
1067/// On every crawl timer tick, also queue a dial attempt for each spare outbound
1068/// connection slot that has a candidate ready to dial, so the peer set keeps
1069/// growing until it reaches `config.peerset_outbound_connection_limit()` or
1070/// runs out of ready candidates.
1071///
1072/// If a handshake fails, restore the unused demand signal by sending it to
1073/// `demand_tx`.
1074///
1075/// The crawler terminates when a crawl or `peerset_tx` returns a
1076/// permanent internal error. Transient errors and individual peer errors should
1077/// be handled within the crawler.
1078///
1079/// If a timer crawl finishes with no outbound connections and no ready candidates,
1080/// re-add the initial peers to the address book, at most once every
1081/// [`constants::MIN_INITIAL_PEER_RECOVERY_INTERVAL`]. This resolves the DNS seeders
1082/// and reloads the disk cache again, and makes failed initial peers eligible for
1083/// another connection attempt after the usual reconnection delay.
1084///
1085/// Uses `active_outbound_connections` to limit the number of active outbound connections
1086/// across both the initial peers and crawler. The limit is based on `config`.
1087#[allow(clippy::too_many_arguments)]
1088#[instrument(
1089    skip(
1090        config,
1091        demand_tx,
1092        demand_rx,
1093        next_peer_service,
1094        crawl_service,
1095        address_book_service,
1096        outbound_connector,
1097        peerset_tx,
1098        active_outbound_connections,
1099        address_book_updater,
1100    ),
1101    fields(
1102        new_peer_interval = ?config.crawl_new_peer_interval,
1103    )
1104)]
1105async fn crawl_and_dial<C, S>(
1106    config: Config,
1107    demand_tx: futures::channel::mpsc::Sender<MorePeers>,
1108    mut demand_rx: futures::channel::mpsc::Receiver<MorePeers>,
1109    next_peer_service: NextPeerService,
1110    crawl_service: CrawlService<S>,
1111    address_book_service: AddressBookService,
1112    outbound_connector: C,
1113    peerset_tx: futures::channel::mpsc::Sender<DiscoveredPeer>,
1114    mut active_outbound_connections: ActiveConnectionCounter,
1115    address_book_updater: AddressBookChangeSender,
1116) -> Result<(), BoxError>
1117where
1118    C: Service<
1119            OutboundConnectorRequest,
1120            Response = (PeerSocketAddr, peer::Client),
1121            Error = BoxError,
1122        > + Clone
1123        + Send
1124        + 'static,
1125    C::Future: Send + 'static,
1126    S: Service<Request, Response = Response, Error = BoxError> + Clone + Send + Sync + 'static,
1127    S::Future: Send + 'static,
1128{
1129    use CrawlerAction::*;
1130
1131    info!(
1132        crawl_new_peer_interval = ?config.crawl_new_peer_interval,
1133        outbound_connections = ?active_outbound_connections.update_count(),
1134        "starting the peer address crawler",
1135    );
1136
1137    // # Concurrency
1138    //
1139    // The candidate selection and crawl services are cheap cloneable handles,
1140    // sharing their rate limits across clones. So tasks using them can be
1141    // spawned and run concurrently, without any locking. Previously, Zebra
1142    // has had deadlocks and long hangs caused by running dependent candidate
1143    // set futures in the same async task.
1144
1145    // Dropping the crawler also aborts unfinished crawls and outbound handshakes.
1146    let mut handshakes = JoinSet::new();
1147
1148    let mut crawl_timer = tokio::time::interval(config.crawl_new_peer_interval);
1149    // If the crawl is delayed, also delay all future crawls.
1150    // (Shorter intervals just add load, without any benefit.)
1151    crawl_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
1152
1153    let mut crawl_timer = IntervalStream::new(crawl_timer).map(|tick| TimerCrawl { tick });
1154
1155    // On Regtest, or without any configured peers or disk cache, there is nothing to re-add.
1156    let has_initial_peer_sources = !config.initial_peer_hostnames().is_empty()
1157        || (config.cache_dir.is_enabled() && !config.network.is_regtest());
1158    let mut last_initial_peer_readd: Option<Instant> = None;
1159
1160    // # Concurrency
1161    //
1162    // To avoid hangs and starvation, the crawler must spawn a separate task for each crawl
1163    // and handshake, so they can make progress independently (and avoid deadlocking each other).
1164    loop {
1165        metrics::gauge!(
1166            "crawler.in_flight_handshakes",
1167            "network" => network_kind_label(&config.network),
1168        )
1169        // Precision loss only affects this diagnostic count; usize values fit within f64's range.
1170        .set(handshakes.len() as f64);
1171
1172        let crawler_action = tokio::select! {
1173            biased;
1174            // Check for completed handshakes first, because the rest of the app needs them.
1175            // Pending handshakes are limited by the connection limit.
1176            next_handshake_res = handshakes.join_next(), if !handshakes.is_empty() => {
1177                match next_handshake_res
1178                    .expect("the handshake set is not empty")
1179                    .panic_if_task_has_panicked()
1180                {
1181                    Ok(action) => action,
1182                    Err(_cancelled) => continue,
1183                }
1184            },
1185            // The timer is rate-limited
1186            next_timer = crawl_timer.next() => Ok(next_timer.expect("timers never terminate")),
1187            // Turn any new demand into an action, based on the crawler's current state.
1188            //
1189            // # Concurrency
1190            //
1191            // Demand is potentially unlimited, so it must go last in a biased select!.
1192            next_demand = demand_rx.next() => next_demand.ok_or("demand stream closed, is Zebra shutting down?".into()).map(|MorePeers|{
1193                if active_outbound_connections.update_count() >= config.peerset_outbound_connection_limit() {
1194                    // Too many open outbound connections or pending handshakes already
1195                    DemandDrop
1196                } else {
1197                    DemandHandshakeOrCrawl
1198                }
1199            })
1200        };
1201
1202        match crawler_action {
1203            // Dummy actions
1204            Ok(DemandDrop) => {
1205                // This is set to trace level because when the peerset is
1206                // congested it can generate a lot of demand signal very rapidly.
1207                trace!("too many open connections or in-flight handshakes, dropping demand signal");
1208            }
1209
1210            // Spawned tasks
1211            Ok(DemandHandshakeOrCrawl) => {
1212                let mut next_peer_service = next_peer_service.clone();
1213                let crawl_service = crawl_service.clone();
1214                let outbound_connector = outbound_connector.clone();
1215                let peerset_tx = peerset_tx.clone();
1216                let address_book_updater = address_book_updater.clone();
1217                let demand_tx = demand_tx.clone();
1218                let network = config.network.clone();
1219
1220                // Increment the connection count before we spawn the connection.
1221                let outbound_connection_tracker = active_outbound_connections.track_connection();
1222                let outbound_connections = active_outbound_connections.update_count();
1223                debug!(?outbound_connections, "opening an outbound peer connection");
1224
1225                // Spawn each handshake or crawl into an independent task, so handshakes can make
1226                // progress while crawls are running.
1227                //
1228                // # Concurrency
1229                //
1230                // The peer crawler must be able to make progress even if some handshakes are
1231                // rate-limited. So the next peer pacing is awaited inside the spawned task.
1232                handshakes.spawn(
1233                    async move {
1234                        // Try to get the next available peer for a handshake.
1235                        //
1236                        // The next peer request is served by the address book updater
1237                        // task, so it shouldn't hang.
1238                        let candidate = next_reconnect_peer(&mut next_peer_service).await;
1239
1240                        if let Some(candidate) = candidate {
1241                            // we don't need to spawn here, because there's nothing running concurrently
1242                            dial(
1243                                network,
1244                                candidate,
1245                                outbound_connector,
1246                                outbound_connection_tracker,
1247                                outbound_connections,
1248                                peerset_tx,
1249                                address_book_updater,
1250                                demand_tx,
1251                            )
1252                            .await?;
1253
1254                            Ok(HandshakeFinished)
1255                        } else {
1256                            // There weren't any peers, so try to get more peers.
1257                            debug!("demand for peers but no available candidates");
1258
1259                            crawl(crawl_service, demand_tx).await?;
1260
1261                            Ok(DemandCrawlFinished)
1262                        }
1263                    }
1264                    .in_current_span(),
1265                );
1266            }
1267            Ok(TimerCrawl { tick }) => {
1268                let crawl_service = crawl_service.clone();
1269                let address_book_service = address_book_service.clone();
1270                let crawl_demand_tx = demand_tx.clone();
1271                let spare_capacity = config
1272                    .peerset_outbound_connection_limit()
1273                    .saturating_sub(active_outbound_connections.update_count());
1274
1275                handshakes.spawn(
1276                    async move {
1277                        debug!(
1278                            ?tick,
1279                            spare_capacity,
1280                            "crawling for more peers in response to the crawl timer"
1281                        );
1282
1283                        // Keep trying to fill the peer set up to the outbound connection limit.
1284                        queue_ready_candidate_demand(
1285                            &address_book_service,
1286                            crawl_demand_tx.clone(),
1287                            spare_capacity,
1288                        )
1289                        .await;
1290
1291                        crawl(crawl_service, crawl_demand_tx).await?;
1292
1293                        // The crawl may have found candidates, so refresh the recovery snapshot.
1294                        let ready_candidates = ready_peer_count(&address_book_service).await;
1295                        Ok(TimerCrawlFinished { ready_candidates })
1296                    }
1297                    .in_current_span(),
1298                );
1299            }
1300
1301            // Completed spawned tasks
1302            Ok(HandshakeFinished) => {
1303                // Already logged in dial()
1304            }
1305            Ok(DemandCrawlFinished) => {
1306                // This is set to trace level because when the peerset is
1307                // congested it can generate a lot of demand signal very rapidly.
1308                trace!("demand-based crawl finished");
1309            }
1310            Ok(TimerCrawlFinished { ready_candidates }) => {
1311                debug!("timer-based crawl finished");
1312
1313                let readd_is_due = last_initial_peer_readd.is_none_or(|last_readd| {
1314                    last_readd.elapsed() >= constants::MIN_INITIAL_PEER_RECOVERY_INTERVAL
1315                });
1316
1317                // Inbound peers don't stop a re-add: outbound peers are chosen by this node,
1318                // so they are harder for an attacker to control.
1319                if has_initial_peer_sources
1320                    && readd_is_due
1321                    && ready_candidates == 0
1322                    && active_outbound_connections.update_count() == 0
1323                {
1324                    warn!(
1325                        "no outbound peer connections and no peer addresses ready to connect to, \
1326                         adding the initial peers again. \
1327                         Hint: check the network connection and the configured initial peers",
1328                    );
1329                    last_initial_peer_readd = Some(Instant::now());
1330
1331                    let config = config.clone();
1332                    let address_book_service = address_book_service.clone();
1333                    let demand_tx = demand_tx.clone();
1334                    // There are no outbound connections, so every outbound slot is spare.
1335                    let spare_capacity = config.peerset_outbound_connection_limit();
1336
1337                    handshakes.spawn(
1338                        async move {
1339                            // Resolving DNS retries until it finds a peer when there are no
1340                            // cached peers, so stop it before the next re-add.
1341                            let re_add = tokio::time::timeout(
1342                                constants::INITIAL_PEER_RECOVERY_TIMEOUT,
1343                                limit_initial_peers(&config, &address_book_service),
1344                            )
1345                            .await;
1346                            if re_add.is_err() {
1347                                info!(
1348                                    timeout = ?constants::INITIAL_PEER_RECOVERY_TIMEOUT,
1349                                    "timed out resolving the initial peers, \
1350                                     retrying after the next recovery interval",
1351                                );
1352                            }
1353
1354                            let ready_candidates = queue_ready_candidate_demand(
1355                                &address_book_service,
1356                                demand_tx,
1357                                spare_capacity,
1358                            )
1359                            .await;
1360
1361                            Ok(InitialPeersReadded { ready_candidates })
1362                        }
1363                        .in_current_span(),
1364                    );
1365                }
1366            }
1367            Ok(InitialPeersReadded { ready_candidates }) => {
1368                info!(?ready_candidates, "finished adding the initial peers again");
1369            }
1370
1371            // Fatal errors and shutdowns
1372            Err(error) => {
1373                info!(?error, "crawler task exiting due to an error");
1374                return Err(error);
1375            }
1376        }
1377
1378        // Security: Let other tasks run after each crawler action is processed.
1379        //
1380        // Avoids remote peers starving other Zebra tasks using outbound connection errors.
1381        tokio::task::yield_now().await;
1382    }
1383}
1384
1385/// Queue a dial attempt using `demand_tx` for each of the `spare_capacity` outbound slots
1386/// that has a candidate ready to dial. Returns the number of ready candidates.
1387///
1388/// Capping the queued attempts at the ready candidate count avoids spawning fallback crawls
1389/// for demand that can't be met. The demand handler re-checks the connection limit before
1390/// each handshake, so excess signals are dropped, and failed handshakes restore their
1391/// demand signal.
1392async fn queue_ready_candidate_demand(
1393    address_book_service: &AddressBookService,
1394    mut demand_tx: futures::channel::mpsc::Sender<MorePeers>,
1395    spare_capacity: usize,
1396) -> usize {
1397    let ready_candidates = ready_peer_count(address_book_service).await;
1398
1399    for _ in 0..spare_capacity.min(ready_candidates) {
1400        if demand_tx.try_send(MorePeers).is_err() {
1401            break;
1402        }
1403    }
1404
1405    ready_candidates
1406}
1407
1408/// Try to get more peers using `crawl_service`, then queue a connection attempt using `demand_tx`.
1409/// If there were no new peers, the connection attempt is skipped.
1410#[instrument(skip(crawl_service, demand_tx))]
1411async fn crawl<S>(
1412    mut crawl_service: CrawlService<S>,
1413    mut demand_tx: futures::channel::mpsc::Sender<MorePeers>,
1414) -> Result<(), BoxError>
1415where
1416    S: Service<Request, Response = Response, Error = BoxError> + Clone + Send + Sync + 'static,
1417    S::Future: Send + 'static,
1418{
1419    // Crawls have timeouts, and are served without locks,
1420    // so this call shouldn't hang.
1421    let more_peers = match crawl_once(&mut crawl_service, None).await {
1422        Ok(more_peers) => more_peers,
1423        Err(e) => {
1424            info!(
1425                ?e,
1426                "crawl service returned an error, is Zebra shutting down?"
1427            );
1428            return Err(e);
1429        }
1430    };
1431
1432    // If we got more peers, try to connect to a new peer on our next loop.
1433    //
1434    // # Security
1435    //
1436    // Crawls are rate-limited by the crawl service,
1437    // and we only try peers if a crawl actually ran.
1438    //
1439    // So if all peers have had a recent attempt, and there was recent crawl
1440    // with no peers, the channel will drain. This prevents useless crawl attempt
1441    // loops.
1442    if let Some(more_peers) = more_peers {
1443        if let Err(send_error) = demand_tx.try_send(more_peers) {
1444            if send_error.is_disconnected() {
1445                // Zebra is shutting down
1446                return Err(send_error.into());
1447            }
1448        }
1449    }
1450
1451    Ok(())
1452}
1453
1454/// Try to connect to `candidate` using `outbound_connector`.
1455/// Uses `outbound_connection_tracker` to track the active connection count.
1456///
1457/// On success, sends peers to `peerset_tx`.
1458/// On failure, marks the peer as failed in the address book,
1459/// then re-adds demand to `demand_tx`.
1460#[allow(clippy::too_many_arguments)]
1461#[instrument(skip(
1462    outbound_connector,
1463    outbound_connection_tracker,
1464    outbound_connections,
1465    peerset_tx,
1466    address_book_updater,
1467    demand_tx
1468))]
1469async fn dial<C>(
1470    network: Network,
1471    candidate: MetaAddr,
1472    mut outbound_connector: C,
1473    outbound_connection_tracker: ConnectionTracker,
1474    outbound_connections: usize,
1475    mut peerset_tx: futures::channel::mpsc::Sender<DiscoveredPeer>,
1476    address_book_updater: AddressBookChangeSender,
1477    mut demand_tx: futures::channel::mpsc::Sender<MorePeers>,
1478) -> Result<(), BoxError>
1479where
1480    C: Service<
1481            OutboundConnectorRequest,
1482            Response = (PeerSocketAddr, peer::Client),
1483            Error = BoxError,
1484        > + Clone
1485        + Send
1486        + 'static,
1487    C::Future: Send + 'static,
1488{
1489    // If Zebra only has a few connections, we log connection failures at info level,
1490    // so users can diagnose and fix the problem. This defines the threshold for info logs.
1491    const MAX_CONNECTIONS_FOR_INFO_LOG: usize = 5;
1492
1493    // # Correctness
1494    //
1495    // To avoid hangs, the dialer must only await:
1496    // - functions that return immediately, or
1497    // - functions that have a reasonable timeout
1498
1499    debug!(?candidate.addr, "attempting outbound connection in response to demand");
1500
1501    // the connector is always ready, so this can't hang
1502    let outbound_connector = outbound_connector.ready().await?;
1503
1504    let req = OutboundConnectorRequest {
1505        addr: candidate.addr,
1506        connection_tracker: outbound_connection_tracker,
1507    };
1508
1509    // the handshake has timeouts, so it shouldn't hang
1510    record_connection_attempt_started(&network, ConnectionDirection::Outbound, candidate.addr);
1511    let handshake_result: Result<(PeerSocketAddr, peer::Client), BoxError> =
1512        outbound_connector.call(req).map(Into::into).await;
1513    record_connection_attempt_finished(
1514        &network,
1515        ConnectionDirection::Outbound,
1516        candidate.addr,
1517        handshake_result.as_ref().err(),
1518    );
1519
1520    match handshake_result {
1521        Ok((address, client)) => {
1522            debug!(?candidate.addr, "successfully dialed new peer");
1523
1524            // The connection limit makes sure this send doesn't block.
1525            peerset_tx.send((address, client)).await?;
1526        }
1527        // The connection was never opened, or it failed the handshake and was dropped.
1528        Err(error) => {
1529            // Silence verbose info logs in production, but keep logs if the number of connections is low.
1530            // Also silence them completely in tests.
1531            if outbound_connections <= MAX_CONNECTIONS_FOR_INFO_LOG && !cfg!(test) {
1532                info!(?error, ?candidate.addr, "failed to make outbound connection to peer");
1533            } else {
1534                debug!(?error, ?candidate.addr, "failed to make outbound connection to peer");
1535            }
1536            report_failed(address_book_updater.clone(), candidate).await;
1537
1538            // The demand signal that was taken out of the queue to attempt to connect to the
1539            // failed candidate never turned into a connection, so add it back.
1540            //
1541            // # Security
1542            //
1543            // Handshake failures are rate-limited by peer attempt timeouts.
1544            if let Err(send_error) = demand_tx.try_send(MorePeers) {
1545                if send_error.is_disconnected() {
1546                    // Zebra is shutting down
1547                    return Err(send_error.into());
1548                }
1549            }
1550        }
1551    }
1552
1553    Ok(())
1554}
1555
1556/// Mark `addr` as a failed peer to `address_book_updater`.
1557#[instrument(skip(address_book_updater))]
1558async fn report_failed(address_book_updater: AddressBookChangeSender, addr: MetaAddr) {
1559    // The connection info is the same as what's already in the address book.
1560    let addr = MetaAddr::new_errored(addr.addr, None);
1561
1562    // Ignore send errors on Zebra shutdown.
1563    let _ = address_book_updater.send(addr).await;
1564}