Skip to main content

zebra_network/peer/
connection.rs

1//! Zebra's per-peer connection state machine.
2//!
3//! Maps the external Zcash/Bitcoin protocol to Zebra's internal request/response
4//! protocol.
5//!
6//! This module contains a lot of undocumented state, assumptions and invariants.
7//! And it's unclear if these assumptions match the `zcashd` implementation.
8//! It should be refactored into a cleaner set of request/response pairs (#1515).
9
10use std::{borrow::Cow, collections::HashSet, fmt, pin::Pin, sync::Arc, time::Instant};
11
12use futures::{future::Either, prelude::*};
13use rand::{seq::SliceRandom, RngExt};
14use tokio::time::Sleep;
15use tower::{Service, ServiceExt};
16use tracing::Instrument;
17
18use zebra_chain::{
19    block::{self, Block},
20    chain_tip::{ChainTip, NoChainTip},
21    serialization::SerializationError,
22    transaction::{UnminedTx, UnminedTxId},
23};
24
25use crate::{
26    constants::{
27        GETDATA_MAX_BLOCK_COUNT, MAX_ADDRS_IN_MESSAGE, MAX_FIND_BLOCKS_RESPONSE_HASHES,
28        MAX_OVERLOAD_DROP_PROBABILITY, MIN_OVERLOAD_DROP_PROBABILITY, OVERLOAD_PROTECTION_INTERVAL,
29        PEER_ADDR_RESPONSE_LIMIT,
30    },
31    meta_addr::MetaAddr,
32    peer::{
33        connection::peer_tx::PeerTx, error::AlreadyErrored, ClientRequest, ClientRequestReceiver,
34        ConnectionInfo, ErrorSlot, InProgressClientRequest, MinimumPeerVersion,
35        MustUseClientResponseSender, PeerError, SharedPeerError,
36    },
37    peer_set::{BlockAdvert, ConnectionTracker},
38    protocol::{
39        external::{types::Nonce, InventoryHash, Message},
40        internal::{InventoryResponse, Request, Response},
41    },
42    BoxError, PeerSocketAddr, MAX_TX_INV_IN_SENT_MESSAGE,
43};
44
45use InventoryResponse::*;
46
47mod compact_relay;
48mod peer_tx;
49
50#[cfg(test)]
51mod tests;
52
53#[derive(Debug)]
54pub(super) enum Handler {
55    /// Indicates that the handler has finished processing the request.
56    /// An error here is scoped to the request.
57    Finished(Result<Response, PeerError>),
58    Ping {
59        nonce: Nonce,
60        ping_sent_at: Instant,
61    },
62    Peers,
63    FindBlocks,
64    FindHeaders,
65    BlocksByHash {
66        pending_hashes: HashSet<block::Hash>,
67        blocks: Vec<Arc<Block>>,
68    },
69    CompactBlock {
70        reconstruction: crate::compact::Reconstruction,
71        permit: tokio::sync::OwnedSemaphorePermit,
72        /// The deadline of the whole block download, including a fallback to the full block.
73        deadline: tokio::time::Instant,
74    },
75    TransactionsById {
76        pending_ids: HashSet<UnminedTxId>,
77        transactions: Vec<UnminedTx>,
78    },
79    MempoolTransactionIds,
80}
81
82impl fmt::Display for Handler {
83    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84        f.write_str(&match self {
85            Handler::Finished(Ok(response)) => format!("Finished({response})"),
86            Handler::Finished(Err(error)) => format!("Finished({error})"),
87
88            Handler::Ping { .. } => "Ping".to_string(),
89            Handler::Peers => "Peers".to_string(),
90
91            Handler::FindBlocks => "FindBlocks".to_string(),
92            Handler::FindHeaders => "FindHeaders".to_string(),
93            Handler::CompactBlock { .. } => "CompactBlock".to_string(),
94            Handler::BlocksByHash {
95                pending_hashes,
96                blocks,
97            } => format!(
98                "BlocksByHash {{ pending_hashes: {}, blocks: {} }}",
99                pending_hashes.len(),
100                blocks.len()
101            ),
102
103            Handler::TransactionsById {
104                pending_ids,
105                transactions,
106            } => format!(
107                "TransactionsById {{ pending_ids: {}, transactions: {} }}",
108                pending_ids.len(),
109                transactions.len()
110            ),
111            Handler::MempoolTransactionIds => "MempoolTransactionIds".to_string(),
112        })
113    }
114}
115
116impl Handler {
117    /// Returns the Zebra internal handler type as a string.
118    pub fn command(&self) -> Cow<'static, str> {
119        match self {
120            Handler::Finished(Ok(response)) => format!("Finished({})", response.command()).into(),
121            Handler::Finished(Err(PeerError::Serialization(_))) => "Finished(Serialization)".into(),
122            Handler::Finished(Err(error)) => format!("Finished({})", error.kind()).into(),
123
124            Handler::Ping { .. } => "Ping".into(),
125            Handler::Peers => "Peers".into(),
126
127            Handler::FindBlocks => "FindBlocks".into(),
128            Handler::FindHeaders => "FindHeaders".into(),
129
130            Handler::BlocksByHash { .. } => "BlocksByHash".into(),
131            Handler::CompactBlock { .. } => "CompactBlock".into(),
132            Handler::TransactionsById { .. } => "TransactionsById".into(),
133
134            Handler::MempoolTransactionIds => "MempoolTransactionIds".into(),
135        }
136    }
137
138    /// Try to handle `msg` as a response to a client request, possibly consuming
139    /// it in the process.
140    ///
141    /// This function is where we statefully interpret Bitcoin/Zcash messages
142    /// into responses to messages in the internal request/response protocol.
143    /// This conversion is done by a sequence of (request, message) match arms,
144    /// each of which contains the conversion logic for that pair.
145    ///
146    /// Taking ownership of the message means that we can pass ownership of its
147    /// contents to responses without additional copies.  If the message is not
148    /// interpretable as a response, we return ownership to the caller.
149    ///
150    /// Unexpected messages are left unprocessed, and may be rejected later.
151    ///
152    /// `addr` responses are limited to avoid peer set takeover. Any excess
153    /// addresses are stored in `cached_addrs`.
154    fn process_message(
155        &mut self,
156        msg: Message,
157        cached_addrs: &mut Vec<MetaAddr>,
158        transient_addr: Option<PeerSocketAddr>,
159    ) -> Option<Message> {
160        let mut ignored_msg = None;
161        // TODO: can this be avoided?
162        let tmp_state = std::mem::replace(self, Handler::Finished(Ok(Response::Nil)));
163
164        debug!(handler = %tmp_state, %msg, "received peer response to Zebra request");
165
166        *self = match (tmp_state, msg) {
167            (
168                Handler::Ping {
169                    nonce,
170                    ping_sent_at,
171                },
172                Message::Pong(rsp_nonce),
173            ) => {
174                if nonce == rsp_nonce {
175                    let duration = ping_sent_at.elapsed();
176                    Handler::Finished(Ok(Response::Pong(duration)))
177                } else {
178                    Handler::Ping {
179                        nonce,
180                        ping_sent_at,
181                    }
182                }
183            }
184
185            (Handler::Peers, Message::Addr(new_addrs)) => {
186                // Security: This method performs security-sensitive operations, see its comments
187                // for details.
188                let response_addrs =
189                    Handler::update_addr_cache(cached_addrs, &new_addrs, PEER_ADDR_RESPONSE_LIMIT);
190
191                debug!(
192                    new_addrs = new_addrs.len(),
193                    response_addrs = response_addrs.len(),
194                    remaining_addrs = cached_addrs.len(),
195                    PEER_ADDR_RESPONSE_LIMIT,
196                    "responding to Peers request using new and cached addresses",
197                );
198
199                Handler::Finished(Ok(Response::Peers(response_addrs)))
200            }
201
202            // Requested transactions can be interleaved with unsolicited or duplicate messages.
203            (
204                Handler::TransactionsById {
205                    mut pending_ids,
206                    mut transactions,
207                },
208                Message::Tx(transaction),
209            ) => {
210                if pending_ids.remove(&transaction.id) {
211                    transactions.push(transaction);
212                } else {
213                    ignored_msg = Some(Message::Tx(transaction));
214                }
215
216                if pending_ids.is_empty() {
217                    let available = transactions
218                        .into_iter()
219                        .map(|t| InventoryResponse::Available((t, transient_addr)));
220                    Handler::Finished(Ok(Response::Transactions(available.collect())))
221                } else {
222                    // Keep on waiting for more.
223                    Handler::TransactionsById {
224                        pending_ids,
225                        transactions,
226                    }
227                }
228            }
229            // `zcashd` peers actually return this response.
230            // A `notfound` naming none of the pending IDs is for a cancelled request or
231            // unsolicited, so it isn't a response to this request.
232            (
233                Handler::TransactionsById {
234                    pending_ids,
235                    transactions,
236                },
237                Message::NotFound(missing_invs),
238            ) if transaction_ids(&missing_invs).any(|id| pending_ids.contains(&id)) => {
239                // assumptions:
240                //   - the peer eventually returns a transaction or a `notfound` entry
241                //     for each hash
242                //   - all `notfound` entries are contained in a single message
243                //   - the `notfound` message comes after the transaction messages
244                //
245                // If we're in sync with the peer, then the `notfound` should contain the remaining
246                // hashes from the handler. If we're not in sync with the peer, we should return
247                // what we got so far.
248                let missing_transaction_ids: HashSet<_> = transaction_ids(&missing_invs).collect();
249                if missing_transaction_ids != pending_ids {
250                    trace!(?missing_invs, ?missing_transaction_ids, ?pending_ids);
251                    // if these errors are noisy, we should replace them with debugs
252                    debug!("unexpected notfound message from peer: all remaining transaction hashes should be listed in the notfound. Using partial received transactions as the peer response");
253                }
254                if missing_transaction_ids.len() != missing_invs.len() {
255                    trace!(?missing_invs, ?missing_transaction_ids, ?pending_ids);
256                    debug!("unexpected notfound message from peer: notfound contains duplicate hashes or non-transaction hashes. Using partial received transactions as the peer response");
257                }
258
259                if transactions.is_empty() {
260                    // If we didn't get anything we wanted, retry the request.
261                    let missing_transaction_ids = pending_ids.into_iter().map(Into::into).collect();
262                    Handler::Finished(Err(PeerError::NotFoundResponse(missing_transaction_ids)))
263                } else {
264                    // If we got some of what we wanted, let the internal client know.
265                    let available = transactions
266                        .into_iter()
267                        .map(|t| InventoryResponse::Available((t, transient_addr)));
268                    let missing = pending_ids.into_iter().map(InventoryResponse::Missing);
269
270                    Handler::Finished(Ok(Response::Transactions(
271                        available.chain(missing).collect(),
272                    )))
273                }
274            }
275
276            // `zcashd` returns requested blocks in a single batch of messages.
277            // Other blocks or non-blocks messages can come before or after the batch.
278            // `zcashd` silently skips missing blocks, rather than sending a final `notfound` message.
279            // https://github.com/zcash/zcash/blob/e7b425298f6d9a54810cb7183f00be547e4d9415/src/main.cpp#L5523
280            (
281                Handler::BlocksByHash {
282                    mut pending_hashes,
283                    mut blocks,
284                },
285                Message::Block(block),
286            ) => {
287                // assumptions:
288                //   - the block messages are sent in a single continuous batch
289                //   - missing blocks are silently skipped
290                //     (there is no `notfound` message at the end of the batch)
291                if pending_hashes.remove(&block.hash()) {
292                    // we are in the middle of the continuous block messages
293                    blocks.push(block);
294                } else {
295                    // We got a block we didn't ask for.
296                    //
297                    // So either:
298                    // 1. The response is for a previously cancelled block request.
299                    //    We should treat that block as an inbound gossiped block,
300                    //    and wait for the actual response.
301                    // 2. The peer doesn't know any of the blocks we asked for.
302                    //    We should cancel the request, so we don't hang waiting for blocks that
303                    //    will never arrive.
304                    // 3. The peer sent an unsolicited block.
305                    //    We should treat that block as an inbound gossiped block,
306                    //    and wait for the actual response.
307                    //
308                    // We ignore the message, so we don't desynchronize with the peer. This happens
309                    // when we cancel a request and send a second different request, but receive a
310                    // response for the first request. If we ended the request then, we could send
311                    // a third request to the peer, and end up having to end that request as well
312                    // when the response for the second request arrives.
313                    //
314                    // Ignoring the message gives us a chance to synchronize back to the correct
315                    // request. If that doesn't happen, this request times out.
316                    //
317                    // In case 2, if peers respond with a `notfound` message,
318                    // the cascading errors don't happen. The `notfound` message cancels our request,
319                    // and we know we are in sync with the peer.
320                    //
321                    // Zebra sends `notfound` in response to block requests, but `zcashd` doesn't.
322                    // So we need this message workaround, and the related inventory workarounds.
323                    ignored_msg = Some(Message::Block(block));
324                }
325
326                if pending_hashes.is_empty() {
327                    // If we got everything we wanted, let the internal client know.
328                    let available = blocks
329                        .into_iter()
330                        .map(|block| InventoryResponse::Available((block, transient_addr)));
331                    Handler::Finished(Ok(Response::Blocks(available.collect())))
332                } else {
333                    // Keep on waiting for all the blocks we wanted, until we get them or time out.
334                    Handler::BlocksByHash {
335                        pending_hashes,
336                        blocks,
337                    }
338                }
339            }
340            // Peers are allowed to return this response, but `zcashd` never does.
341            // A `notfound` naming none of the pending hashes is for a cancelled request or
342            // unsolicited, so it isn't a response to this request.
343            (
344                Handler::BlocksByHash {
345                    pending_hashes,
346                    blocks,
347                },
348                Message::NotFound(missing_invs),
349            ) if block_hashes(&missing_invs).any(|hash| pending_hashes.contains(&hash)) => {
350                // assumptions:
351                //   - the peer eventually returns a block or a `notfound` entry
352                //     for each hash
353                //   - all `notfound` entries are contained in a single message
354                //   - the `notfound` message comes after the block messages
355                //
356                // If we're in sync with the peer, then the `notfound` should contain the remaining
357                // hashes from the handler. If we're not in sync with the peer, we should return
358                // what we got so far, and log an error.
359                let missing_blocks: HashSet<_> = block_hashes(&missing_invs).collect();
360                if missing_blocks != pending_hashes {
361                    trace!(?missing_invs, ?missing_blocks, ?pending_hashes);
362                    // if these errors are noisy, we should replace them with debugs
363                    debug!("unexpected notfound message from peer: all remaining block hashes should be listed in the notfound. Using partial received blocks as the peer response");
364                }
365                if missing_blocks.len() != missing_invs.len() {
366                    trace!(?missing_invs, ?missing_blocks, ?pending_hashes);
367                    debug!("unexpected notfound message from peer: notfound contains duplicate hashes or non-block hashes. Using partial received blocks as the peer response");
368                }
369
370                if blocks.is_empty() {
371                    // If we didn't get anything we wanted, retry the request.
372                    let missing_block_hashes = pending_hashes.into_iter().map(Into::into).collect();
373                    Handler::Finished(Err(PeerError::NotFoundResponse(missing_block_hashes)))
374                } else {
375                    // If we got some of what we wanted, let the internal client know.
376                    let available = blocks
377                        .into_iter()
378                        .map(|block| InventoryResponse::Available((block, transient_addr)));
379                    let missing = pending_hashes.into_iter().map(InventoryResponse::Missing);
380
381                    Handler::Finished(Ok(Response::Blocks(available.chain(missing).collect())))
382                }
383            }
384
385            // The peer can send the full block while its compact block's missing transactions are
386            // recovered, for example when it answers an earlier request for the block. The full
387            // block is the response that a fallback request would get.
388            (Handler::CompactBlock { reconstruction, .. }, Message::Block(block))
389                if block.hash() == reconstruction.block_hash() =>
390            {
391                Handler::Finished(Ok(Response::Blocks(vec![InventoryResponse::Available((
392                    block,
393                    transient_addr,
394                ))])))
395            }
396
397            // Inventory has no request identifier: a block announcement is indistinguishable
398            // from a valid singleton reply. Keep accepting these replies.
399            // An empty inventory can be a late mempool reply after cancellation.
400            // Zebra and zcashd send no message for an empty getblocks result.
401            (Handler::FindBlocks, Message::Inv(items))
402                if !items.is_empty()
403                    && items
404                        .iter()
405                        .all(|item| matches!(item, InventoryHash::Block(_))) =>
406            {
407                // Truncate rather than reject: zcashd can add one extra hash to a full
408                // 500-hash response, and a peer can always send 500 junk hashes anyway.
409                Handler::Finished(Ok(Response::BlockHashes(
410                    block_hashes(&items[..])
411                        .take(MAX_FIND_BLOCKS_RESPONSE_HASHES)
412                        .collect(),
413                )))
414            }
415            // A compact block announces the peer's new tip, like a single block inventory. So
416            // it completes the tip poll, and it is also handled as an announcement. Otherwise
417            // the poll would hold this connection until it times out, and the announced block's
418            // download with it.
419            (Handler::FindBlocks, Message::CompactBlock(block)) => {
420                let hash = block.header.hash();
421                ignored_msg = Some(Message::CompactBlock(block));
422                Handler::Finished(Ok(Response::BlockHashes(vec![hash])))
423            }
424            (Handler::FindHeaders, Message::Headers(headers)) => {
425                Handler::Finished(Ok(Response::BlockHeaders(headers)))
426            }
427
428            // Transaction announcements and mempool replies use the same wire message.
429            // An empty inventory is also a valid reply from a peer with an empty mempool.
430            (Handler::MempoolTransactionIds, Message::Inv(items))
431                if items.iter().all(|item| item.unmined_tx_id().is_some()) =>
432            {
433                Handler::Finished(Ok(Response::TransactionIds(
434                    transaction_ids(&items).collect(),
435                )))
436            }
437
438            // By default, messages are not responses.
439            (state, msg) => {
440                trace!(?msg, "did not interpret message as response");
441                ignored_msg = Some(msg);
442                state
443            }
444        };
445
446        ignored_msg
447    }
448
449    /// Adds `new_addrs` to the `cached_addrs` cache, then takes and returns `response_size`
450    /// addresses from that cache.
451    ///
452    /// `cached_addrs` can be empty if the cache is empty. `new_addrs` can be empty or `None` if
453    /// there are no new addresses. `response_size` can be zero or `None` if there is no response
454    /// needed.
455    fn update_addr_cache<'new>(
456        cached_addrs: &mut Vec<MetaAddr>,
457        new_addrs: impl IntoIterator<Item = &'new MetaAddr>,
458        response_size: impl Into<Option<usize>>,
459    ) -> Vec<MetaAddr> {
460        // # Peer Set Reliability
461        //
462        // Newly received peers are added to the cache, so that we can use them if the connection
463        // doesn't respond to our getaddr requests.
464        //
465        // Add the new addresses to the end of the cache.
466        cached_addrs.extend(new_addrs.into_iter().cloned());
467
468        // # Security
469        //
470        // We limit how many peer addresses we take from each peer, so that our address book
471        // and outbound connections aren't controlled by a single peer (#1869). We randomly select
472        // peers, so the remote peer can't control which addresses we choose by changing the order
473        // in the messages they send.
474        let response_size = response_size.into().unwrap_or_default();
475
476        let mut temp_cache = Vec::new();
477        std::mem::swap(cached_addrs, &mut temp_cache);
478
479        // The response is fully shuffled, remaining is partially shuffled.
480        let (response, remaining) = temp_cache.partial_shuffle(&mut rand::rng(), response_size);
481
482        // # Security
483        //
484        // The cache size is limited to avoid memory denial of service.
485        //
486        // It's ok to just partially shuffle the cache, because it doesn't actually matter which
487        // peers we drop. Having excess peers is rare, because most peers only send one large
488        // unsolicited peer message when they first connect.
489        *cached_addrs = remaining.to_vec();
490        cached_addrs.truncate(MAX_ADDRS_IN_MESSAGE);
491
492        response.to_vec()
493    }
494}
495
496#[derive(Debug)]
497#[must_use = "AwaitingResponse.tx.send() must be called before drop"]
498pub(super) enum State {
499    /// Awaiting a client request or a peer message.
500    AwaitingRequest,
501    /// Awaiting a peer message we can interpret as a response to a client request.
502    AwaitingResponse {
503        handler: Handler,
504        tx: MustUseClientResponseSender,
505        span: tracing::Span,
506    },
507    /// A failure has occurred and we are shutting down the connection.
508    Failed,
509}
510
511impl fmt::Display for State {
512    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
513        f.write_str(&match self {
514            State::AwaitingRequest => "AwaitingRequest".to_string(),
515            State::AwaitingResponse { handler, .. } => {
516                format!("AwaitingResponse({handler})")
517            }
518            State::Failed => "Failed".to_string(),
519        })
520    }
521}
522
523impl State {
524    /// Returns the Zebra internal state as a string.
525    pub fn command(&self) -> Cow<'static, str> {
526        match self {
527            State::AwaitingRequest => "AwaitingRequest".into(),
528            State::AwaitingResponse { handler, .. } => {
529                format!("AwaitingResponse({})", handler.command()).into()
530            }
531            State::Failed => "Failed".into(),
532        }
533    }
534}
535
536/// The outcome of mapping an inbound [`Message`] to a [`Request`].
537#[derive(Clone, Debug, Eq, PartialEq)]
538#[must_use = "inbound messages must be handled"]
539pub enum InboundMessage {
540    /// The message was mapped to an inbound [`Request`].
541    AsRequest(Request),
542
543    /// The message was consumed by the mapping method.
544    ///
545    /// For example, it could be cached, treated as an error,
546    /// or an internally handled [`Message::Ping`].
547    Consumed,
548
549    /// The message was not used by the inbound message handler.
550    Unused,
551}
552
553impl From<Request> for InboundMessage {
554    fn from(request: Request) -> Self {
555        InboundMessage::AsRequest(request)
556    }
557}
558
559/// The channels, services, and associated state for a peer connection.
560pub struct Connection<S, Tx, C = NoChainTip>
561where
562    Tx: Sink<Message, Error = SerializationError> + Unpin,
563{
564    /// The metadata for the connected peer `service`.
565    ///
566    /// This field is used for debugging.
567    pub connection_info: Arc<ConnectionInfo>,
568
569    /// The state of this connection's current request or response.
570    pub(super) state: State,
571
572    /// The response sender for a client request, while that request is being sent to the peer.
573    ///
574    /// # Security
575    ///
576    /// The connection task can be cancelled while it waits for a slow peer to accept a request,
577    /// for example when the peer set drops a busy [`Client`](super::Client). A response sender
578    /// held by the request future would then be dropped unused, which panics. Instead, the
579    /// connection holds the sender, so [`Connection::shutdown()`] sends an error on it when the
580    /// connection is dropped.
581    sending_request_tx: Option<MustUseClientResponseSender>,
582
583    /// A timeout for a client request. This is stored separately from
584    /// State so that we can move the future out of it independently of
585    /// other state handling.
586    pub(super) request_timer: Option<Pin<Box<Sleep>>>,
587
588    /// Unused peers from recent `addr` or `addrv2` messages from this peer.
589    /// Also holds the initial addresses sent in `version` messages, or guessed from the remote IP.
590    ///
591    /// When peers send solicited or unsolicited peer advertisements, Zebra puts them in this cache.
592    ///
593    /// When Zebra's components request peers, some cached peers are randomly selected,
594    /// consumed, and returned as a modified response. This works around `zcashd`'s address
595    /// response rate-limit.
596    ///
597    /// The cache size is limited to avoid denial of service attacks.
598    pub(super) cached_addrs: Vec<MetaAddr>,
599
600    /// The `inbound` service, used to answer requests from this connection's peer.
601    pub(super) svc: S,
602
603    /// A channel for requests that Zebra's internal services want to send to remote peers.
604    ///
605    /// This channel accepts [`Request`]s, and produces [`InProgressClientRequest`]s.
606    pub(super) client_rx: ClientRequestReceiver,
607
608    /// Receives block adverts independently of the current request's response.
609    pub(super) block_advert_rx: tokio::sync::mpsc::Receiver<BlockAdvert>,
610
611    /// Permit decoding recovery responses only for the live request and its deadline.
612    pub(super) compact_recovery:
613        Option<tokio::sync::watch::Sender<Option<crate::compact::ExpectedBlockTransactions>>>,
614
615    /// Registers the blocks that this peer announces in compact form, once their announcements
616    /// are handled.
617    pub(super) compact_inventory:
618        Option<tokio::sync::broadcast::Sender<crate::peer_set::InventoryChange>>,
619
620    /// Live authorization, rechecked immediately before request and advert writes.
621    minimum_peer_version: MinimumPeerVersion<C>,
622    bans_receiver: tokio::sync::watch::Receiver<crate::BanList>,
623
624    /// A slot for an error shared between the Connection and the Client that uses it.
625    ///
626    /// `None` unless the connection or client have errored.
627    pub(super) error_slot: ErrorSlot,
628
629    /// A channel for sending Zcash messages to the connected peer.
630    ///
631    /// This channel accepts [`Message`]s.
632    ///
633    /// The corresponding peer message receiver is passed to [`Connection::run`].
634    pub(super) peer_tx: PeerTx<Tx>,
635
636    /// A connection tracker that reduces the open connection count when dropped.
637    /// Used to limit the number of open connections in Zebra.
638    ///
639    /// This field does nothing until it is dropped.
640    ///
641    /// # Security
642    ///
643    /// If this connection tracker or `Connection`s are leaked,
644    /// the number of active connections will appear higher than it actually is.
645    /// If enough connections leak, Zebra will stop making new connections.
646    #[allow(dead_code)]
647    pub(super) connection_tracker: ConnectionTracker,
648
649    /// The address label for peer logs. Usually the remote IP and port.
650    pub(super) metrics_label: String,
651
652    /// The state for this peer, when the metrics were last updated.
653    pub(super) last_metrics_state: Option<Cow<'static, str>>,
654
655    /// The time of the last overload error response from the inbound
656    /// service to a request from this connection,
657    /// or None if this connection hasn't yet received an overload error.
658    last_overload_time: Option<Instant>,
659
660    /// Negotiated compact transport and globally bounded, expiring body retention.
661    compact: compact_relay::CompactRelay,
662}
663
664impl<S, Tx, C> fmt::Debug for Connection<S, Tx, C>
665where
666    Tx: Sink<Message, Error = SerializationError> + Unpin,
667{
668    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
669        // skip the channels, they don't tell us anything useful
670        f.debug_struct(std::any::type_name::<Self>())
671            .field("connection_info", &self.connection_info)
672            .field("state", &self.state)
673            .field("request_timer", &self.request_timer)
674            .field("cached_addrs", &self.cached_addrs.len())
675            .field("error_slot", &self.error_slot)
676            .field("metrics_label", &self.metrics_label)
677            .field("last_metrics_state", &self.last_metrics_state)
678            .field("last_overload_time", &self.last_overload_time)
679            .finish()
680    }
681}
682
683impl<S, Tx, C> Connection<S, Tx, C>
684where
685    Tx: Sink<Message, Error = SerializationError> + Unpin,
686{
687    /// Return a new connection from its channels, services, shared state, and metadata.
688    pub(crate) fn new(
689        inbound_service: S,
690        (client_rx, block_advert_rx, minimum_peer_version, bans_receiver): (
691            futures::channel::mpsc::Receiver<ClientRequest>,
692            tokio::sync::mpsc::Receiver<BlockAdvert>,
693            MinimumPeerVersion<C>,
694            tokio::sync::watch::Receiver<crate::BanList>,
695        ),
696        error_slot: ErrorSlot,
697        peer_tx: Tx,
698        connection_tracker: ConnectionTracker,
699        connection_info: Arc<ConnectionInfo>,
700        initial_cached_addrs: Vec<MetaAddr>,
701    ) -> Self {
702        let metrics_label = connection_info.connected_addr.get_transient_addr_label();
703
704        Connection {
705            connection_info,
706            state: State::AwaitingRequest,
707            sending_request_tx: None,
708            request_timer: None,
709            cached_addrs: initial_cached_addrs,
710            svc: inbound_service,
711            client_rx: client_rx.into(),
712            block_advert_rx,
713            compact_recovery: None,
714            compact_inventory: None,
715            minimum_peer_version,
716            bans_receiver,
717            error_slot,
718            peer_tx: peer_tx.into(),
719            connection_tracker,
720            metrics_label,
721            last_metrics_state: None,
722            last_overload_time: None,
723            compact: compact_relay::CompactRelay::default(),
724        }
725    }
726}
727
728impl<S, Tx, C> Connection<S, Tx, C>
729where
730    S: Service<Request, Response = Response, Error = BoxError>,
731    S::Error: Into<BoxError>,
732    C: ChainTip,
733    Tx: Sink<Message, Error = SerializationError> + Unpin,
734{
735    /// Consume this `Connection` to form a spawnable future containing its event loop.
736    ///
737    /// `peer_rx` is a channel for receiving Zcash [`Message`]s from the connected peer.
738    /// The corresponding peer message receiver is [`Connection::peer_tx`].
739    pub async fn run<Rx>(mut self, mut peer_rx: Rx)
740    where
741        Rx: Stream<Item = Result<Message, SerializationError>> + Unpin,
742    {
743        // Ask negotiated peers to announce new blocks in compact form.
744        if self.connection_info.early_block_relay {
745            let request = Message::SendCompact {
746                high_bandwidth: true,
747                version: 1,
748            };
749            if let Err(error) = self.peer_tx.send(request).await {
750                self.fail_with(error).await;
751            }
752        }
753        // At a high level, the event loop we want is as follows: we check for any
754        // incoming messages from the remote peer, check if they should be interpreted
755        // as a response to a pending client request, and if not, interpret them as a
756        // request from the remote peer to our node.
757        //
758        // We also need to handle those client requests in the first place. The client
759        // requests are received from the corresponding `peer::Client` over a bounded
760        // channel (with bound 1, to minimize buffering), but there is no relationship
761        // between the stream of client requests and the stream of peer messages, so we
762        // cannot ignore one kind while waiting on the other. Moreover, we cannot accept
763        // a second client request while the first one is still pending.
764        //
765        // To do this, we inspect the current request state.
766        //
767        // If there is no pending request, we wait on either an incoming peer message or
768        // an incoming request, whichever comes first.
769        //
770        // If there is a pending request, peer messages can complete it. Block adverts use a
771        // separate channel in either state because they do not expect a response.
772        //
773        // TODO: turn this comment into a module-level comment, after splitting the module.
774        loop {
775            // # Security
776            //
777            // The framed reader returns the messages already in its buffer without polling the
778            // socket, and messages that need no reply never reach the yields in
779            // `drive_peer_request`. So a peer that floods us with them could keep this task
780            // running without a break, delaying the other tasks on its runtime worker.
781            //
782            // Charging every iteration to the task's cooperative budget makes the task yield
783            // to the scheduler once the budget runs out, whatever the peer sends.
784            tokio::task::coop::consume_budget().await;
785
786            self.compact.expire();
787            let compact_expiry = self.compact.expiry();
788            self.update_state_metrics(None);
789
790            match self.state {
791                State::AwaitingRequest => {
792                    trace!("awaiting client request or peer message");
793                    // # Correctness
794                    //
795                    // Peer messages precede adverts so a ready GetBlocks request gets its response
796                    // first; otherwise the peer could mistake our advert for that response.
797                    // Adverts precede ordinary client requests because they need no response.
798                    // Ordinary client requests follow peer messages to avoid confusing unsolicited
799                    // inventory with a response to a new request.
800                    //
801                    // This improves the performance of peer responses to Zebra requests, and new
802                    // peer requests to Zebra's inbound service.
803                    //
804                    // `futures::StreamExt::next()` is cancel-safe:
805                    // <https://docs.rs/tokio/latest/tokio/macro.select.html#cancellation-safety>
806                    // This means that messages from the future that isn't selected stay in the stream,
807                    // and they will be returned next time the future is checked.
808                    //
809                    // If an inbound peer message arrives at a ready peer that also has a pending
810                    // request from Zebra, we want to process the peer's message first.
811                    // If we process the Zebra request first:
812                    // - we could misinterpret the inbound peer message as a response to the Zebra
813                    //   request, or
814                    // - if the peer message is a request to Zebra, and we put the peer in the
815                    //   AwaitingResponse state, then we'll correctly ignore the simultaneous Zebra
816                    //   request. (Zebra services make multiple requests or retry, so this is ok.)
817                    //
818                    // # Security
819                    //
820                    // If a peer sends an uninterrupted series of messages, it will delay any new
821                    // requests from Zebra to that individual peer. This is behaviour we want,
822                    // because:
823                    // - any responses to Zebra's requests to that peer would be slow or timeout,
824                    // - the peer will eventually fail a Zebra keepalive check and get disconnected,
825                    // - if there are too many inbound messages overall, the inbound service will
826                    //   return an overload error and the peer will be disconnected.
827                    //
828                    // Messages to other peers will continue to be processed concurrently. Some
829                    // Zebra services might be temporarily delayed until the peer times out, if a
830                    // request to that peer is sent by the service, and the service blocks until
831                    // the request completes (or times out).
832                    let incoming = tokio::select! {
833                        biased;
834                        _ = tokio::time::sleep_until(compact_expiry), if self.compact.has_cached() => continue,
835                        msg = peer_rx.next() => Either::Left(msg),
836                        // A closed advert channel disables only this branch.
837                        Some(hash) = self.block_advert_rx.recv() => {
838                            self.send_block_advert(hash).await;
839                            continue;
840                        }
841                        req = self.client_rx.next() => Either::Right(req),
842                    };
843                    match incoming {
844                        Either::Left(None) => {
845                            self.fail_with(PeerError::ConnectionClosed).await;
846                        }
847                        Either::Left(Some(Err(e))) => self.fail_with(e).await,
848                        Either::Left(Some(Ok(msg))) => {
849                            let unhandled_msg = self.handle_message_as_request(msg).await;
850
851                            if let Some(unhandled_msg) = unhandled_msg {
852                                debug!(
853                                    %unhandled_msg,
854                                    "ignoring unhandled request while awaiting a request"
855                                );
856                            }
857                        }
858                        Either::Right(None) => {
859                            trace!("client_rx closed, ending connection");
860
861                            // There are no requests to be flushed,
862                            // but we need to set an error and update metrics.
863                            // (We don't want to log this error, because it's normal behaviour.)
864                            self.shutdown_async(PeerError::ClientDropped).await;
865                            break;
866                        }
867                        Either::Right(Some(req)) => {
868                            let span = req.span.clone();
869                            self.handle_client_request(req).instrument(span).await
870                        }
871                    }
872                }
873
874                // Check whether the handler is finished before waiting for a response message,
875                // because the response might be `Nil` or synthetic.
876                State::AwaitingResponse {
877                    handler: Handler::Finished(_),
878                    ref span,
879                    ..
880                } => {
881                    // We have to get rid of the span reference so we can tamper with the state.
882                    let span = span.clone();
883                    trace!(
884                        parent: &span,
885                        "returning completed response to client request"
886                    );
887
888                    // Replace the state with a temporary value,
889                    // so we can take ownership of the response sender.
890                    let tmp_state = std::mem::replace(&mut self.state, State::Failed);
891
892                    if let State::AwaitingResponse {
893                        handler: Handler::Finished(response),
894                        tx,
895                        ..
896                    } = tmp_state
897                    {
898                        if let Ok(response) = response.as_ref() {
899                            debug!(%response, "finished receiving peer response to Zebra request");
900                            // Add a metric for inbound responses to outbound requests.
901                            metrics::counter!(
902                                "zebra.net.in.responses",
903                                "command" => response.command(),
904                            )
905                            .increment(1);
906                        } else {
907                            debug!(error = ?response, "error in peer response to Zebra request");
908                        }
909
910                        // A peer that negotiated compact block relay can send a block before it
911                        // has validated it. The downloaders score these blocks' failures
912                        // differently, so their downloads are marked.
913                        let response = match response {
914                            Ok(Response::Blocks(blocks))
915                                if self.connection_info.early_block_relay =>
916                            {
917                                Ok(Response::EarlyBlocks(blocks))
918                            }
919                            response => response,
920                        };
921                        let _ = tx.send(response.map_err(Into::into));
922                    } else {
923                        unreachable!("already checked for AwaitingResponse");
924                    }
925
926                    self.state = State::AwaitingRequest;
927                }
928
929                // We're awaiting a response to a client request,
930                // so also wait on cancellation, timeout, and response-free block adverts.
931                State::AwaitingResponse {
932                    ref span,
933                    ref mut tx,
934                    ..
935                } => {
936                    // we have to get rid of the span reference so we can tamper with the state
937                    let span = span.clone();
938                    trace!(parent: &span, "awaiting response to client request");
939                    let timer_ref = self
940                        .request_timer
941                        .as_mut()
942                        .expect("timeout must be set while awaiting response");
943
944                    // # Security
945                    //
946                    // Biased selection preserves cancellation and timeout priority.
947                    //
948                    // If multiple futures are ready, we want the priority for each individual
949                    // connection to be:
950                    // - cancellation, then
951                    // - timeout, then
952                    // - peer messages, then
953                    // - block adverts.
954                    //
955                    // (Messages to other peers are processed concurrently.)
956                    //
957                    // This makes sure a peer can't block disconnection or timeouts by sending too
958                    // many messages. It also avoids doing work to process messages after a
959                    // connection has failed.
960                    // Peer messages precede adverts to preserve response ordering, as above.
961                    let peer_msg = tokio::select! {
962                        biased;
963                        _ = tx.cancellation() => {
964                            // The canceled response receiver no longer needs a result.
965                            trace!(parent: &span, "client request was cancelled");
966                            self.clear_compact_recovery();
967                            self.state = State::AwaitingRequest;
968                            continue;
969                        }
970                        _ = timer_ref => {
971                            if let State::AwaitingResponse { handler: Handler::CompactBlock { reconstruction, deadline, .. }, .. } = &self.state {
972                                let (hash, deadline) = (reconstruction.block_hash(), *deadline);
973                                self.fallback_compact(hash, deadline).await;
974                                continue;
975                            }
976                            trace!(parent: &span, "client request timed out");
977                            let e = PeerError::ConnectionReceiveTimeout;
978
979                            self.state = match std::mem::replace(&mut self.state, State::Failed) {
980                                // Ping timeouts fail the connection, not just the request.
981                                State::AwaitingResponse {
982                                    handler: Handler::Ping { .. },
983                                    tx,
984                                    ..
985                                } => {
986                                    let e = SharedPeerError::from(e);
987                                    let _ = tx.send(Err(e.clone()));
988                                    self.fail_with(e).await;
989                                    State::Failed
990                                }
991                                State::AwaitingResponse { tx, .. } => {
992                                    let _ = tx.send(Err(e.into()));
993                                    State::AwaitingRequest
994                                }
995                                _ => unreachable!(
996                                    "unexpected failed connection state while AwaitingResponse: client_receiver: {:?}",
997                                    self.client_rx
998                                ),
999                            };
1000                            continue;
1001                        }
1002                        _ = tokio::time::sleep_until(compact_expiry), if self.compact.has_cached() => continue,
1003                        msg = peer_rx.next() => msg,
1004                        Some(hash) = self.block_advert_rx.recv() => {
1005                            self.send_block_advert(hash).await;
1006                            continue;
1007                        }
1008                    };
1009                    match peer_msg {
1010                        None => self.fail_with(PeerError::ConnectionClosed).await,
1011                        Some(Err(e)) => self.fail_with(e).await,
1012                        Some(Ok(peer_msg)) => {
1013                            self.update_state_metrics(Some(format_args!(
1014                                "Out::Rsp::{}",
1015                                peer_msg.command()
1016                            )));
1017
1018                            let recovering = matches!(
1019                                self.state,
1020                                State::AwaitingResponse {
1021                                    handler: Handler::CompactBlock { .. },
1022                                    ..
1023                                }
1024                            );
1025
1026                            // Try to process the message using the handler.
1027                            // This extremely awkward construction avoids
1028                            // keeping a live reference to handler across the
1029                            // call to handle_message_as_request, which takes
1030                            // &mut self. This is a sign that we don't properly
1031                            // factor the state required for inbound and
1032                            // outbound requests.
1033                            let request_msg = match self.state {
1034                                State::AwaitingResponse {
1035                                    ref mut handler, ..
1036                                } => span.in_scope(|| handler.process_message(peer_msg, &mut self.cached_addrs, self.connection_info.connected_addr.get_transient_addr())),
1037                                _ => unreachable!("unexpected state after AwaitingResponse: {:?}, peer_msg: {:?}, client_receiver: {:?}",
1038                                                  self.state,
1039                                                  peer_msg,
1040                                                  self.client_rx,
1041                                ),
1042                            };
1043
1044                            self.update_state_metrics(None);
1045
1046                            // A full block can finish compact recovery, so stop decoding
1047                            // transactions for it.
1048                            if recovering
1049                                && !matches!(
1050                                    self.state,
1051                                    State::AwaitingResponse {
1052                                        handler: Handler::CompactBlock { .. },
1053                                        ..
1054                                    }
1055                                )
1056                            {
1057                                self.clear_compact_recovery();
1058                            }
1059
1060                            // If the message was not consumed as a response,
1061                            // check whether it can be handled as a request.
1062                            let unused_msg = if let Some(request_msg) = request_msg {
1063                                // do NOT instrument with the request span, this is
1064                                // independent work
1065                                self.handle_message_as_request(request_msg).await
1066                            } else {
1067                                None
1068                            };
1069
1070                            if let Some(unused_msg) = unused_msg {
1071                                debug!(
1072                                    %unused_msg,
1073                                    %self.state,
1074                                    "ignoring peer message: not a response or a request",
1075                                );
1076                            }
1077                        }
1078                    }
1079                }
1080
1081                // This connection has failed: stop the event loop, and complete the future.
1082                State::Failed => break,
1083            }
1084        }
1085
1086        // TODO: close peer_rx here, after changing it from a stream to a channel
1087
1088        let error = self.error_slot.try_get_error();
1089        assert!(
1090            error.is_some(),
1091            "closing connections must call fail_with() or shutdown() to set the error slot"
1092        );
1093    }
1094
1095    /// Fail this connection, log the failure, and shut it down.
1096    /// See [`Self::shutdown_async()`] for details.
1097    ///
1098    /// Use [`Self::shutdown_async()`] to avoid logging the failure,
1099    /// and [`Self::shutdown()`] from non-async code.
1100    async fn fail_with(&mut self, error: impl Into<SharedPeerError>) {
1101        let error = error.into();
1102
1103        debug!(
1104            %error,
1105            client_receiver = ?self.client_rx,
1106            "failing peer service with error"
1107        );
1108
1109        self.shutdown_async(error).await;
1110    }
1111
1112    /// Acknowledge only completed local writes, after rechecking live authorization.
1113    async fn send_block_advert(&mut self, advert: BlockAdvert) {
1114        if advert.result.is_closed() {
1115            metrics::counter!("peer.canceled").increment(1);
1116            metrics::counter!(
1117                "zebra.net.out.requests.canceled",
1118                "command" => "AdvertiseBlock",
1119            )
1120            .increment(1);
1121            return;
1122        }
1123
1124        metrics::counter!(
1125            "zebra.net.out.requests",
1126            "command" => "AdvertiseBlock",
1127        )
1128        .increment(1);
1129        // Peers that asked for compact announcements get the block's header and short IDs.
1130        let message = self
1131            .compact_advert(advert.hash)
1132            .await
1133            .unwrap_or_else(|| Message::Inv(vec![InventoryHash::Block(advert.hash)]));
1134        let is_compact = matches!(message, Message::CompactBlock(_));
1135
1136        let address = self.connection_info.connected_addr.get_transient_addr();
1137        let version = self.connection_info.remote.version;
1138        let minimum = &mut self.minimum_peer_version;
1139        let bans = &self.bans_receiver;
1140        let delivery = self
1141            .peer_tx
1142            .send_authorized(message, || {
1143                if version >= minimum.current()
1144                    && !address.is_some_and(|addr| bans.borrow().is_banned(addr.ip()))
1145                {
1146                    Ok(())
1147                } else {
1148                    Err(PeerError::AdvertAuthorizationRevoked)
1149                }
1150            })
1151            .await;
1152        match delivery {
1153            Ok(()) => {
1154                if is_compact {
1155                    self.compact.mark_sent();
1156                }
1157                let _ = advert.result.send(Ok(()));
1158            }
1159            Err(error) => {
1160                if is_compact {
1161                    self.compact.clear_sent();
1162                }
1163                let error = SharedPeerError::from(error);
1164                let _ = advert.result.send(Err(error.clone().into()));
1165                self.fail_with(error).await;
1166            }
1167        }
1168    }
1169
1170    /// Handle an internal client request, possibly generating outgoing messages to the
1171    /// remote peer.
1172    ///
1173    /// NOTE: the caller should use .instrument(msg.span) to instrument the function.
1174    async fn handle_client_request(&mut self, req: InProgressClientRequest) {
1175        trace!(?req.request);
1176        use Request::*;
1177        use State::*;
1178        let InProgressClientRequest { request, tx, span } = req;
1179
1180        if tx.is_canceled() {
1181            metrics::counter!("peer.canceled").increment(1);
1182            debug!(state = %self.state, %request, "ignoring canceled request");
1183
1184            metrics::counter!(
1185                "zebra.net.out.requests.canceled",
1186                "command" => request.command(),
1187            )
1188            .increment(1);
1189            self.update_state_metrics(Some(format_args!(
1190                "Out::Req::Canceled::{}",
1191                request.command()
1192            )));
1193
1194            return;
1195        }
1196
1197        debug!(state = %self.state, %request, "sending request from Zebra to peer");
1198
1199        // Add a metric for outbound requests.
1200        metrics::counter!(
1201            "zebra.net.out.requests",
1202            "command" => request.command(),
1203        )
1204        .increment(1);
1205        self.update_state_metrics(Some(format_args!("Out::Req::{}", request.command())));
1206
1207        // # Security
1208        //
1209        // This future can be cancelled while it awaits a send, so the connection must own the
1210        // response sender until the send finishes. See `sending_request_tx` for details.
1211        self.sending_request_tx = Some(tx);
1212
1213        let address = self.connection_info.connected_addr.get_transient_addr();
1214        let version = self.connection_info.remote.version;
1215        let minimum = &mut self.minimum_peer_version;
1216        let bans = &self.bans_receiver;
1217        let mut authorized = || {
1218            if version < minimum.current()
1219                || address.is_some_and(|addr| bans.borrow().is_banned(addr.ip()))
1220            {
1221                Err(PeerError::ConnectionDropped)
1222            } else {
1223                Ok(())
1224            }
1225        };
1226
1227        let new_handler = match (&self.state, request) {
1228            (Failed, request) => panic!(
1229                "failed connection cannot handle new request: {:?}, client_receiver: {:?}",
1230                request,
1231                self.client_rx
1232            ),
1233            (pending @ AwaitingResponse { .. }, request) => panic!(
1234                "tried to process new request: {:?} while awaiting a response: {:?}, client_receiver: {:?}",
1235                request,
1236                pending,
1237                self.client_rx
1238            ),
1239
1240            // Take some cached addresses from the peer connection. This address cache helps
1241            // work-around a `zcashd` addr response rate-limit.
1242            (AwaitingRequest, Peers) if !self.cached_addrs.is_empty() => {
1243                // Security: This method performs security-sensitive operations, see its comments
1244                // for details.
1245                let response_addrs = Handler::update_addr_cache(&mut self.cached_addrs, None, PEER_ADDR_RESPONSE_LIMIT);
1246
1247                debug!(
1248                    response_addrs = response_addrs.len(),
1249                    remaining_addrs = self.cached_addrs.len(),
1250                    PEER_ADDR_RESPONSE_LIMIT,
1251                    "responding to Peers request using some cached addresses",
1252                );
1253
1254                Ok(Handler::Finished(Ok(Response::Peers(response_addrs))))
1255            }
1256            (AwaitingRequest, Peers) => self
1257                .peer_tx
1258                .send_authorized(Message::GetAddr, authorized)
1259                .await
1260                .map(|()| Handler::Peers),
1261
1262            (AwaitingRequest, Ping(nonce)) => {
1263                let ping_sent_at = Instant::now();
1264
1265                self
1266                    .peer_tx
1267                    .send_authorized(Message::Ping(nonce), authorized)
1268                    .await
1269                    .map(|()| Handler::Ping { nonce, ping_sent_at })
1270            }
1271
1272            // A compact announcement from this peer can answer the download without a full body.
1273            (AwaitingRequest, BlockDownload { hash, .. }) if self.compact.is_cached(hash) => {
1274                match authorized() {
1275                    Ok(()) => self.download_block(hash).await,
1276                    Err(error) => Err(error),
1277                }
1278            }
1279            (AwaitingRequest, BlocksByHash(hashes))
1280                if hashes.len() == 1
1281                    && hashes.iter().all(|hash| self.compact.is_cached(*hash)) =>
1282            {
1283                let hash = *hashes.iter().next().expect("the set contains exactly one hash");
1284                match authorized() {
1285                    Ok(()) => self.download_block(hash).await,
1286                    Err(error) => Err(error),
1287                }
1288            }
1289            (AwaitingRequest, BlockDownload { hash, .. }) => self
1290                .peer_tx
1291                .send_authorized(Message::GetData(vec![hash.into()]), authorized)
1292                .await
1293                .map(|()| Handler::BlocksByHash {
1294                    blocks: Vec::with_capacity(1),
1295                    pending_hashes: HashSet::from([hash]),
1296                }),
1297            (AwaitingRequest, BlocksByHash(hashes)) => {
1298                self
1299                    .peer_tx
1300                    .send_authorized(Message::GetData(
1301                        hashes.iter().map(|h| (*h).into()).collect(),
1302                    ), authorized)
1303                    .await
1304                    .map(|()|
1305                         Handler::BlocksByHash {
1306                             blocks: Vec::with_capacity(hashes.len()),
1307                             pending_hashes: hashes,
1308                         }
1309                    )
1310            }
1311            (AwaitingRequest, TransactionsById(ids)) => {
1312                self
1313                    .peer_tx
1314                    .send_authorized(Message::GetData(
1315                        ids.iter().map(Into::into).collect(),
1316                    ), authorized)
1317                    .await
1318                    .map(|()|
1319                         Handler::TransactionsById {
1320                             transactions: Vec::with_capacity(ids.len()),
1321                             pending_ids: ids,
1322                         })
1323            }
1324
1325            (AwaitingRequest, FindBlocks { known_blocks, stop }) => {
1326                self
1327                    .peer_tx
1328                    .send_authorized(Message::GetBlocks { known_blocks, stop }, authorized)
1329                    .await
1330                    .map(|()|
1331                         Handler::FindBlocks
1332                    )
1333            }
1334            (AwaitingRequest, FindHeaders { known_blocks, stop }) => {
1335                self
1336                    .peer_tx
1337                    .send_authorized(Message::GetHeaders { known_blocks, stop }, authorized)
1338                    .await
1339                    .map(|()|
1340                         Handler::FindHeaders
1341                    )
1342            }
1343
1344            (AwaitingRequest, MempoolTransactionIds) => {
1345                self
1346                    .peer_tx
1347                    .send_authorized(Message::Mempool, authorized)
1348                    .await
1349                    .map(|()|
1350                         Handler::MempoolTransactionIds
1351                    )
1352            }
1353
1354            (AwaitingRequest, PushTransaction(transaction, _)) => {
1355                self
1356                    .peer_tx
1357                    .send_authorized(Message::Tx(transaction), authorized)
1358                    .await
1359                    .map(|()|
1360                         Handler::Finished(Ok(Response::Nil))
1361                    )
1362            }
1363            (AwaitingRequest, AdvertiseTransactionIds(hashes, _)) => {
1364                let max_tx_inv_in_message: usize = MAX_TX_INV_IN_SENT_MESSAGE
1365                    .try_into()
1366                    .expect("constant fits in usize");
1367
1368                // # Security
1369                //
1370                // In most cases, we try to split over-sized requests into multiple network-layer
1371                // messages. But we are unlikely to reach this limit with the default mempool
1372                // config, so a gossip like this could indicate a network amplification attack.
1373                //
1374                // This limit is particularly important here, because advertisements send the same
1375                // message to half our available peers.
1376                //
1377                // If there are thousands of transactions in the mempool, letting peers know the
1378                // exact transactions we have isn't that important, so it's ok to drop arbitrary
1379                // transaction hashes from our response.
1380                if hashes.len() > max_tx_inv_in_message {
1381                    debug!(inv_count = ?hashes.len(), ?MAX_TX_INV_IN_SENT_MESSAGE, "unusually large transaction ID gossip");
1382                }
1383
1384                let hashes = hashes.into_iter().take(max_tx_inv_in_message).map(Into::into).collect();
1385
1386                self
1387                    .peer_tx
1388                    .send_authorized(Message::Inv(hashes), authorized)
1389                    .await
1390                    .map(|()|
1391                         Handler::Finished(Ok(Response::Nil))
1392                    )
1393            }
1394            (AwaitingRequest, AdvertiseBlockToAll(_) | AdvertiseBlock(_, _)) => {
1395                Ok(Handler::Finished(Err(PeerError::AdvertRequiresDedicatedService)))
1396            }
1397            (AwaitingRequest, AdvertiseCompactBlock(..) | CheckCompactHeader(_) | CompactBlockTransactions(_) | CheckCompactBlock(_)) => {
1398                Ok(Handler::Finished(Err(PeerError::InboundOnlyRequest)))
1399            }
1400            // The peer set handles this request itself, so there is nothing to send to the peer.
1401            (AwaitingRequest, PollPeerSet) => Ok(Handler::Finished(Ok(Response::Nil))),
1402        };
1403
1404        let tx = self.sending_request_tx.take().expect(
1405            "sender is stored before sending, and the only other place that takes it is \
1406             shutdown(), which the request arms never call",
1407        );
1408
1409        let download_deadline = self.compact.take_download_deadline();
1410
1411        // Update the connection state with a new handler, or fail with an error.
1412        match new_handler {
1413            Ok(handler) => {
1414                let timer = compact_relay::response_timer(&handler, download_deadline);
1415                if let (Handler::CompactBlock { reconstruction, .. }, Some(recovery)) =
1416                    (&handler, &self.compact_recovery)
1417                {
1418                    recovery.send_replace(Some(crate::compact::ExpectedBlockTransactions {
1419                        block_hash: reconstruction.block_hash(),
1420                        count: reconstruction.missing_count(),
1421                        deadline: timer.deadline(),
1422                    }));
1423                }
1424                self.state = AwaitingResponse { handler, span, tx };
1425                self.request_timer = Some(Box::pin(timer));
1426            }
1427            Err(error) => {
1428                let error = SharedPeerError::from(error);
1429                let _ = tx.send(Err(error.clone()));
1430                self.fail_with(error).await;
1431            }
1432        };
1433    }
1434
1435    /// Handle `msg` as a request from a peer to this Zebra instance.
1436    ///
1437    /// If the message is not handled, it is returned.
1438    // This function has its own span, because we're creating a new work
1439    // context (namely, the work of processing the inbound msg as a request)
1440    #[instrument(name = "msg_as_req", skip(self, msg), fields(msg = msg.command()))]
1441    async fn handle_message_as_request(&mut self, msg: Message) -> Option<Message> {
1442        trace!(?msg);
1443        debug!(state = %self.state, %msg, "received inbound peer message");
1444
1445        self.update_state_metrics(Some(format_args!("In::Msg::{}", msg.command())));
1446
1447        use InboundMessage::*;
1448
1449        let req = match msg {
1450            Message::SendCompact {
1451                high_bandwidth,
1452                version,
1453            } => {
1454                self.compact.send =
1455                    self.connection_info.early_block_relay && high_bandwidth && version == 1;
1456                Consumed
1457            }
1458            Message::CompactBlock(block) => {
1459                self.receive_compact(block).await;
1460                return None;
1461            }
1462            Message::GetBlockTransactions(request) => {
1463                self.serve_compact_transactions(request).await;
1464                return None;
1465            }
1466            Message::BlockTransactions(response) => {
1467                self.receive_compact_transactions(response).await;
1468                return None;
1469            }
1470            Message::Ping(nonce) => {
1471                trace!(?nonce, "responding to heartbeat");
1472                if let Err(e) = self.peer_tx.send(Message::Pong(nonce)).await {
1473                    self.fail_with(e).await;
1474                }
1475                Consumed
1476            }
1477            // These messages shouldn't be sent outside of a handshake.
1478            Message::Version { .. } => {
1479                self.fail_with(PeerError::DuplicateHandshake).await;
1480                Consumed
1481            }
1482            Message::Verack => {
1483                self.fail_with(PeerError::DuplicateHandshake).await;
1484                Consumed
1485            }
1486            // These messages should already be handled as a response if they
1487            // could be a response, so if we see them here, they were either
1488            // sent unsolicited, or they were sent in response to a canceled request
1489            // that we've already forgotten about.
1490            Message::Reject { .. } => {
1491                debug!(%msg, "got reject message unsolicited or from canceled request");
1492                Unused
1493            }
1494            Message::NotFound { .. } => {
1495                debug!(%msg, "got notfound message unsolicited or from canceled request");
1496                Unused
1497            }
1498            Message::Pong(_) => {
1499                debug!(%msg, "got pong message unsolicited or from canceled request");
1500                Unused
1501            }
1502            Message::Block(_) => {
1503                debug!(%msg, "got block message unsolicited or from canceled request");
1504                Unused
1505            }
1506            Message::Headers(_) => {
1507                debug!(%msg, "got headers message unsolicited or from canceled request");
1508                Unused
1509            }
1510            // These messages should never be sent by peers.
1511            Message::FilterLoad { .. } | Message::FilterAdd { .. } | Message::FilterClear => {
1512                // # Security
1513                //
1514                // Zcash connections are not authenticated, so malicious nodes can send fake messages,
1515                // with connected peers' IP addresses in the IP header.
1516                //
1517                // Since we can't verify their source, Zebra needs to ignore unexpected messages,
1518                // because closing the connection could cause a denial of service or eclipse attack.
1519                debug!(%msg, "got BIP111 message without advertising NODE_BLOOM");
1520
1521                // Ignored, but consumed because it is technically a protocol error.
1522                Consumed
1523            }
1524
1525            // # Security
1526            //
1527            // Zebra crawls the network proactively, and that's the only way peers get into our
1528            // address book. This prevents peers from filling our address book with malicious peer
1529            // addresses.
1530            Message::Addr(ref new_addrs) => {
1531                // # Peer Set Reliability
1532                //
1533                // We keep a list of the unused peer addresses sent by each connection, to work
1534                // around `zcashd`'s `getaddr` response rate-limit.
1535                let no_response =
1536                    Handler::update_addr_cache(&mut self.cached_addrs, new_addrs, None);
1537                assert_eq!(
1538                    no_response,
1539                    Vec::new(),
1540                    "peers unexpectedly taken from cache"
1541                );
1542
1543                debug!(
1544                    new_addrs = new_addrs.len(),
1545                    cached_addrs = self.cached_addrs.len(),
1546                    "adding unsolicited addresses to cached addresses",
1547                );
1548
1549                Consumed
1550            }
1551            Message::Tx(ref transaction) => Request::PushTransaction(
1552                transaction.clone(),
1553                // Tag the directly pushed transaction with the sending peer so the
1554                // mempool downloader can enforce a per-peer queue cap, just like
1555                // advertised transaction IDs. See `GHSA-m9xx-8rcj-vmgp`.
1556                self.connection_info.connected_addr.get_transient_addr(),
1557            )
1558            .into(),
1559            Message::Inv(ref items) => match &items[..] {
1560                // We don't expect to be advertised multiple blocks at a time,
1561                // so we ignore any advertisements of multiple blocks.
1562                [InventoryHash::Block(hash)] => Request::AdvertiseBlock(
1563                    *hash,
1564                    self.connection_info.connected_addr.get_transient_addr(),
1565                )
1566                .into(),
1567
1568                // Some peers advertise invs with mixed item types.
1569                // But we're just interested in the transaction invs.
1570                //
1571                // TODO: split mixed invs into multiple requests,
1572                //       but skip runs of multiple blocks.
1573                tx_ids if tx_ids.iter().any(|item| item.unmined_tx_id().is_some()) => {
1574                    Request::AdvertiseTransactionIds(
1575                        transaction_ids(items).collect(),
1576                        self.connection_info.connected_addr.get_transient_addr(),
1577                    )
1578                    .into()
1579                }
1580
1581                // Log detailed messages for ignored inv advertisement messages.
1582                [] => {
1583                    debug!(%msg, "ignoring empty inv");
1584
1585                    // A reply can arrive after its mempool or block-locator request was canceled.
1586                    Unused
1587                }
1588                [InventoryHash::Block(_), InventoryHash::Block(_), ..] => {
1589                    debug!(%msg, "ignoring inv with multiple blocks");
1590                    Unused
1591                }
1592                _ => {
1593                    debug!(%msg, "ignoring inv with no transactions");
1594                    Unused
1595                }
1596            },
1597            Message::GetData(ref items) => match &items[..] {
1598                // Some peers advertise invs with mixed item types.
1599                // So we suspect they might do the same with getdata.
1600                //
1601                // Since we can only handle one message at a time,
1602                // we treat it as a block request if there are any blocks,
1603                // or a transaction request if there are any transactions.
1604                //
1605                // TODO: split mixed getdata into multiple requests.
1606                b_hashes
1607                    if b_hashes
1608                        .iter()
1609                        .any(|item| matches!(item, InventoryHash::Block(_))) =>
1610                {
1611                    // Bound the set before cloning it for inbound dispatch. Duplicates do not
1612                    // consume slots, matching the inbound service's distinct-hash limit.
1613                    let mut hashes =
1614                        HashSet::with_capacity(items.len().min(GETDATA_MAX_BLOCK_COUNT));
1615                    for hash in block_hashes(items) {
1616                        hashes.insert(hash);
1617                        if hashes.len() == GETDATA_MAX_BLOCK_COUNT {
1618                            break;
1619                        }
1620                    }
1621                    Request::BlocksByHash(hashes).into()
1622                }
1623                tx_ids if tx_ids.iter().any(|item| item.unmined_tx_id().is_some()) => {
1624                    Request::TransactionsById(transaction_ids(items).collect()).into()
1625                }
1626
1627                // Log detailed messages for ignored getdata request messages.
1628                [] => {
1629                    debug!(%msg, "ignoring empty getdata");
1630
1631                    // This might be a minor protocol error, or it might mean "not found".
1632                    Unused
1633                }
1634                _ => {
1635                    debug!(%msg, "ignoring getdata with no blocks or transactions");
1636                    Unused
1637                }
1638            },
1639            Message::GetAddr => Request::Peers.into(),
1640            Message::GetBlocks {
1641                ref known_blocks,
1642                stop,
1643            } => Request::FindBlocks {
1644                known_blocks: known_blocks.clone(),
1645                stop,
1646            }
1647            .into(),
1648            Message::GetHeaders {
1649                ref known_blocks,
1650                stop,
1651            } => Request::FindHeaders {
1652                known_blocks: known_blocks.clone(),
1653                stop,
1654            }
1655            .into(),
1656            Message::Mempool => Request::MempoolTransactionIds.into(),
1657        };
1658
1659        // Handle the request, and return unused messages.
1660        match req {
1661            AsRequest(req) => {
1662                self.drive_peer_request(req).await;
1663                None
1664            }
1665            Consumed => None,
1666            Unused => Some(msg),
1667        }
1668    }
1669
1670    /// Given a `req` originating from the peer, drive it to completion and send
1671    /// any appropriate messages to the remote peer. If an error occurs while
1672    /// processing the request (e.g., the service is shedding load), then we call
1673    /// fail_with to terminate the entire peer connection, shrinking the number
1674    /// of connected peers.
1675    async fn drive_peer_request(&mut self, req: Request) {
1676        trace!(?req);
1677
1678        // Add a metric for inbound requests
1679        metrics::counter!(
1680            "zebra.net.in.requests",
1681            "command" => req.command(),
1682        )
1683        .increment(1);
1684        self.update_state_metrics(Some(format_args!("In::Req::{}", req.command())));
1685
1686        // Give the inbound service time to clear its queue,
1687        // before sending the next inbound request.
1688        tokio::task::yield_now().await;
1689
1690        // # Security
1691        //
1692        // Holding buffer slots for a long time can cause hangs:
1693        // <https://docs.rs/tower/latest/tower/buffer/struct.Buffer.html#a-note-on-choosing-a-bound>
1694        //
1695        // The inbound service must be called immediately after a buffer slot is reserved.
1696        //
1697        // The inbound service never times out in readiness, because the load shed layer is always
1698        // ready, and returns an error in response to the request instead.
1699        if self.svc.ready().await.is_err() {
1700            self.fail_with(PeerError::ServiceShutdown).await;
1701            return;
1702        }
1703
1704        // Inbound service request timeouts are handled by the timeout layer in `start::start()`.
1705        let rsp = match self.svc.call(req.clone()).await {
1706            Err(e) => {
1707                if e.is::<tower::load_shed::error::Overloaded>() {
1708                    // # Security
1709                    //
1710                    // The peer request queue must have a limited length.
1711                    // The buffer and load shed layers are added in `start::start()`.
1712                    tracing::debug!("inbound service is overloaded, may close connection");
1713
1714                    let now = Instant::now();
1715
1716                    self.handle_inbound_overload(req, now, PeerError::Overloaded)
1717                        .await;
1718                } else if e.is::<tower::timeout::error::Elapsed>() {
1719                    // # Security
1720                    //
1721                    // Peer requests must have a timeout.
1722                    // The timeout layer is added in `start::start()`.
1723                    tracing::info!(%req, "inbound service request timed out, may close connection");
1724
1725                    let now = Instant::now();
1726
1727                    self.handle_inbound_overload(req, now, PeerError::InboundTimeout)
1728                        .await;
1729                } else {
1730                    // We could send a reject to the remote peer, but that might cause
1731                    // them to disconnect, and we might be using them to sync blocks.
1732                    // For similar reasons, we don't want to fail_with() here - we
1733                    // only close the connection if the peer is doing something wrong.
1734                    info!(
1735                        %e,
1736                        connection_state = ?self.state,
1737                        client_receiver = ?self.client_rx,
1738                        "error processing peer request",
1739                    );
1740                    self.update_state_metrics(Some(format_args!(
1741                        "In::Req::{}/Rsp::Error",
1742                        req.command()
1743                    )));
1744                }
1745
1746                return;
1747            }
1748            Ok(rsp) => rsp,
1749        };
1750
1751        // Add a metric for outbound responses to inbound requests
1752        metrics::counter!(
1753            "zebra.net.out.responses",
1754            "command" => rsp.command(),
1755        )
1756        .increment(1);
1757        self.update_state_metrics(Some(format_args!("In::Rsp::{}", rsp.command())));
1758
1759        // TODO: split response handler into its own method
1760        match rsp.clone() {
1761            Response::Nil => { /* generic success, do nothing */ }
1762            Response::CompactBlockTransactions(_) | Response::EarlyBlocks(_) => {
1763                error!("inbound service returned a local-only compact relay response");
1764                return;
1765            }
1766            Response::Peers(addrs) => {
1767                if let Err(e) = self.peer_tx.send(Message::Addr(addrs)).await {
1768                    self.fail_with(e).await;
1769                }
1770            }
1771            Response::Pong(duration) => {
1772                debug!(?duration, "responding to Ping with Pong RTT");
1773            }
1774            Response::Transactions(transactions) => {
1775                // Generate one tx message per transaction,
1776                // then a notfound message with all the missing transaction ids.
1777                let mut missing_ids = Vec::new();
1778
1779                for transaction in transactions.into_iter() {
1780                    match transaction {
1781                        Available((transaction, _)) => {
1782                            if let Err(e) = self.peer_tx.send(Message::Tx(transaction)).await {
1783                                self.fail_with(e).await;
1784                                return;
1785                            }
1786                        }
1787                        Missing(id) => missing_ids.push(id.into()),
1788                    }
1789                }
1790
1791                if !missing_ids.is_empty() {
1792                    if let Err(e) = self.peer_tx.send(Message::NotFound(missing_ids)).await {
1793                        self.fail_with(e).await;
1794                        return;
1795                    }
1796                }
1797            }
1798            Response::Blocks(blocks) => {
1799                // Generate one tx message per block,
1800                // then a notfound message with all the missing block hashes.
1801                let mut missing_hashes = Vec::new();
1802
1803                for block in blocks.into_iter() {
1804                    match block {
1805                        Available((block, _)) => {
1806                            if let Err(e) = self.peer_tx.send(Message::Block(block)).await {
1807                                self.fail_with(e).await;
1808                                return;
1809                            }
1810                        }
1811                        Missing(hash) => missing_hashes.push(hash.into()),
1812                    }
1813                }
1814
1815                if !missing_hashes.is_empty() {
1816                    if let Err(e) = self.peer_tx.send(Message::NotFound(missing_hashes)).await {
1817                        self.fail_with(e).await;
1818                        return;
1819                    }
1820                }
1821            }
1822            // Like zcashd, send nothing for an empty `getblocks` result, so an empty inventory only
1823            // ever answers an empty mempool.
1824            Response::BlockHashes(hashes) if hashes.is_empty() => {}
1825            Response::BlockHashes(hashes) => {
1826                if let Err(e) = self
1827                    .peer_tx
1828                    .send(Message::Inv(hashes.into_iter().map(Into::into).collect()))
1829                    .await
1830                {
1831                    self.fail_with(e).await
1832                }
1833            }
1834            Response::BlockHeaders(headers) => {
1835                if let Err(e) = self.peer_tx.send(Message::Headers(headers)).await {
1836                    self.fail_with(e).await
1837                }
1838            }
1839            Response::TransactionIds(hashes) => {
1840                let max_tx_inv_in_message: usize = MAX_TX_INV_IN_SENT_MESSAGE
1841                    .try_into()
1842                    .expect("constant fits in usize");
1843
1844                // # Security
1845                //
1846                // In most cases, we try to split over-sized responses into multiple network-layer
1847                // messages. But we are unlikely to reach this limit with the default mempool
1848                // config, so a response like this could indicate a network amplification attack.
1849                //
1850                // If there are thousands of transactions in the mempool, letting peers know the
1851                // exact transactions we have isn't that important, so it's ok to drop arbitrary
1852                // transaction hashes from our response.
1853                if hashes.len() > max_tx_inv_in_message {
1854                    debug!(inv_count = ?hashes.len(), ?MAX_TX_INV_IN_SENT_MESSAGE, "unusually large transaction ID response");
1855                }
1856
1857                let hashes = hashes
1858                    .into_iter()
1859                    .take(max_tx_inv_in_message)
1860                    .map(Into::into)
1861                    .collect();
1862
1863                if let Err(e) = self.peer_tx.send(Message::Inv(hashes)).await {
1864                    self.fail_with(e).await
1865                }
1866            }
1867        }
1868
1869        debug!(state = %self.state, %req, %rsp, "sent Zebra response to peer");
1870
1871        // Give the inbound service time to clear its queue,
1872        // before checking the connection for the next inbound or outbound request.
1873        tokio::task::yield_now().await;
1874    }
1875
1876    /// Handle inbound service overload and timeout error responses by randomly terminating some
1877    /// connections.
1878    ///
1879    /// # Security
1880    ///
1881    /// When the inbound service is overloaded with requests, Zebra needs to drop some connections,
1882    /// to reduce the load on the application. But dropping every connection that receives an
1883    /// `Overloaded` error from the inbound service could cause Zebra to drop too many peer
1884    /// connections, and stop itself downloading blocks or transactions.
1885    ///
1886    /// Malicious or misbehaving peers can also overload the inbound service, and make Zebra drop
1887    /// its connections to other peers.
1888    ///
1889    /// So instead, Zebra drops some overloaded connections at random. If a connection has recently
1890    /// overloaded the inbound service, it is more likely to be dropped. This makes it harder for a
1891    /// single peer (or multiple peers) to perform a denial of service attack.
1892    ///
1893    /// The inbound connection rate-limit also makes it hard for multiple peers to perform this
1894    /// attack, because each inbound connection can only send one inbound request before its
1895    /// probability of being disconnected increases.
1896    async fn handle_inbound_overload(&mut self, req: Request, now: Instant, error: PeerError) {
1897        let prev = self.last_overload_time.replace(now);
1898        let drop_connection_probability = overload_drop_connection_probability(now, prev);
1899
1900        if rand::rng().random::<f32>() < drop_connection_probability {
1901            if matches!(error, PeerError::Overloaded) {
1902                metrics::counter!("pool.closed.loadshed").increment(1);
1903            } else {
1904                metrics::counter!("pool.closed.inbound.timeout").increment(1);
1905            }
1906
1907            tracing::info!(
1908                drop_connection_probability = format!("{drop_connection_probability:.3}"),
1909                remote_user_agent = ?self.connection_info.remote.user_agent,
1910                negotiated_version = ?self.connection_info.negotiated_version,
1911                peer = ?self.metrics_label,
1912                last_peer_state = ?self.last_metrics_state,
1913                // TODO: remove this detailed debug info once #6506 is fixed
1914                remote_height = ?self.connection_info.remote.start_height,
1915                cached_addrs = ?self.cached_addrs.len(),
1916                connection_state = ?self.state,
1917                "inbound service {error} error, closing connection",
1918            );
1919
1920            self.update_state_metrics(Some(format_args!(
1921                "In::Req::{}/Rsp::{error}::Error",
1922                req.command()
1923            )));
1924            self.fail_with(error).await;
1925        } else {
1926            self.update_state_metrics(Some(format_args!(
1927                "In::Req::{}/Rsp::{error}::Ignored",
1928                req.command()
1929            )));
1930
1931            if matches!(error, PeerError::Overloaded) {
1932                metrics::counter!("pool.ignored.loadshed").increment(1);
1933            } else {
1934                metrics::counter!("pool.ignored.inbound.timeout").increment(1);
1935            }
1936        }
1937    }
1938}
1939
1940/// Returns the probability of dropping a connection where the last overload was at `prev`,
1941/// and the current overload is `now`.
1942///
1943/// # Security
1944///
1945/// Connections that haven't seen an overload error in the past OVERLOAD_PROTECTION_INTERVAL
1946/// have a small chance of being closed (MIN_OVERLOAD_DROP_PROBABILITY).
1947///
1948/// Connections that have seen a previous overload error in that time
1949/// have a higher chance of being dropped up to MAX_OVERLOAD_DROP_PROBABILITY.
1950/// This probability increases quadratically, so peers that send lots of inbound
1951/// requests are more likely to be dropped.
1952///
1953/// ## Examples
1954///
1955/// If a connection sends multiple overloads close together, it is very likely to be
1956/// disconnected. If a connection has two overloads multiple seconds apart, it is unlikely
1957/// to be disconnected.
1958fn overload_drop_connection_probability(now: Instant, prev: Option<Instant>) -> f32 {
1959    let Some(prev) = prev else {
1960        return MIN_OVERLOAD_DROP_PROBABILITY;
1961    };
1962
1963    let protection_fraction_since_last_overload =
1964        (now - prev).as_secs_f32() / OVERLOAD_PROTECTION_INTERVAL.as_secs_f32();
1965
1966    // Quadratically increase the disconnection probability for very recent overloads.
1967    // Negative values are ignored by clamping to MIN_OVERLOAD_DROP_PROBABILITY.
1968    let overload_fraction = protection_fraction_since_last_overload.powi(2);
1969
1970    let probability_range = MAX_OVERLOAD_DROP_PROBABILITY - MIN_OVERLOAD_DROP_PROBABILITY;
1971    let raw_drop_probability =
1972        MAX_OVERLOAD_DROP_PROBABILITY - (overload_fraction * probability_range);
1973
1974    raw_drop_probability.clamp(MIN_OVERLOAD_DROP_PROBABILITY, MAX_OVERLOAD_DROP_PROBABILITY)
1975}
1976
1977impl<S, Tx, C> Connection<S, Tx, C>
1978where
1979    Tx: Sink<Message, Error = SerializationError> + Unpin,
1980{
1981    /// Update the connection state metrics for this connection,
1982    /// using `extra_state_info` as additional state information.
1983    ///
1984    /// Counts live connections by command, without retaining per-peer address series.
1985    fn update_state_metrics(&mut self, extra_state_info: Option<fmt::Arguments<'_>>) {
1986        let current_metrics_state = if let Some(extra_state_info) = extra_state_info {
1987            format!("{}::{extra_state_info}", self.state.command()).into()
1988        } else {
1989            self.state.command()
1990        };
1991
1992        if self.last_metrics_state.as_ref() == Some(&current_metrics_state) {
1993            return;
1994        }
1995
1996        self.erase_state_metrics();
1997
1998        // Count this connection in the aggregate live-state gauge.
1999        metrics::gauge!(
2000            "zebra.net.connection.state",
2001            "command" => current_metrics_state.clone(),
2002        )
2003        .increment(1.0);
2004
2005        self.last_metrics_state = Some(current_metrics_state);
2006    }
2007
2008    /// Decrement the aggregate connection state gauge for this connection.
2009    fn erase_state_metrics(&mut self) {
2010        if let Some(last_metrics_state) = self.last_metrics_state.take() {
2011            metrics::gauge!(
2012                "zebra.net.connection.state",
2013                "command" => last_metrics_state,
2014            )
2015            .decrement(1.0);
2016        }
2017    }
2018
2019    /// Stop admitting compact recovery responses before dropping or replacing their handler.
2020    fn clear_compact_recovery(&self) {
2021        if let Some(recovery) = &self.compact_recovery {
2022            recovery.send_replace(None);
2023        }
2024    }
2025
2026    /// Drops the compact relay bodies of a connection that is shutting down, which releases their
2027    /// global slots.
2028    ///
2029    /// A peer that stops reading can hold the connection task in its final flush until the
2030    /// connection is dropped, so this runs before that flush.
2031    fn release_compact(&mut self) {
2032        self.clear_compact_recovery();
2033        self.compact.release();
2034        if let State::AwaitingResponse { handler, .. } = &mut self.state {
2035            if matches!(handler, Handler::CompactBlock { .. }) {
2036                // `shutdown()` still answers the request with the connection's error.
2037                *handler = Handler::Finished(Ok(Response::Nil));
2038            }
2039        }
2040    }
2041
2042    /// Marks the peer as having failed with `error`, and performs connection cleanup,
2043    /// including async channel closes.
2044    ///
2045    /// If the connection has errored already, re-use the original error.
2046    /// Otherwise, fail the connection with `error`.
2047    async fn shutdown_async(&mut self, error: impl Into<SharedPeerError>) {
2048        // Close async channels first, so other tasks can start shutting down.
2049        // There's nothing we can do about errors while shutting down, and some errors are expected.
2050        //
2051        // TODO: close peer_tx and peer_rx in shutdown() and Drop, after:
2052        // - using channels instead of streams/sinks?
2053        // - exposing the underlying implementation rather than using generics and closures?
2054        // - adding peer_rx to the connection struct (optional)
2055        self.release_compact();
2056        let _ = self.peer_tx.close().await;
2057
2058        self.shutdown(error);
2059    }
2060
2061    /// Marks the peer as having failed with `error`, and performs connection cleanup.
2062    /// See [`Self::shutdown_async()`] for details.
2063    ///
2064    /// Call [`Self::shutdown_async()`] in async code, because it can shut down more channels.
2065    fn shutdown(&mut self, error: impl Into<SharedPeerError>) {
2066        self.release_compact();
2067        let mut error = error.into();
2068
2069        // Close channels first, so other tasks can start shutting down.
2070        self.client_rx.close();
2071
2072        // Update the shared error slot
2073        //
2074        // # Correctness
2075        //
2076        // Error slots use a threaded `std::sync::Mutex`, so accessing the slot
2077        // can block the async task's current thread. We only perform a single
2078        // slot update per `Client`. We ignore subsequent error slot updates.
2079        let slot_result = self.error_slot.try_update_error(error.clone());
2080
2081        if let Err(AlreadyErrored { original_error }) = slot_result {
2082            debug!(
2083                new_error = %error,
2084                %original_error,
2085                connection_state = ?self.state,
2086                "multiple errors on connection: \
2087                 failed connections should stop processing pending requests and responses, \
2088                 then close the connection"
2089            );
2090
2091            error = original_error;
2092        } else {
2093            debug!(%error,
2094                   connection_state = ?self.state,
2095                   "shutting down peer service with error");
2096        }
2097
2098        // Prepare to flush any pending client requests.
2099        //
2100        // We've already closed the client channel, so setting State::Failed
2101        // will make the main loop flush any pending requests.
2102        //
2103        // However, we may have an outstanding client request in State::AwaitingResponse,
2104        // so we need to deal with it first.
2105        if let State::AwaitingResponse { tx, .. } =
2106            std::mem::replace(&mut self.state, State::Failed)
2107        {
2108            // # Correctness
2109            //
2110            // We know the slot has Some(error), because we just set it above,
2111            // and the error slot is never unset.
2112            //
2113            // Accessing the error slot locks a threaded std::sync::Mutex, which
2114            // can block the current async task thread. We briefly lock the mutex
2115            // to clone the error.
2116            let _ = tx.send(Err(error.clone()));
2117        }
2118
2119        // Or the connection task may have been cancelled while it was sending a client request.
2120        if let Some(tx) = self.sending_request_tx.take() {
2121            let _ = tx.send(Err(error.clone()));
2122        }
2123
2124        // Make the timer and metrics consistent with the Failed state.
2125        self.request_timer = None;
2126        self.update_state_metrics(None);
2127
2128        // Finally, flush pending client requests.
2129        while let Some(InProgressClientRequest { tx, span, .. }) =
2130            self.client_rx.close_and_flush_next()
2131        {
2132            trace!(
2133                parent: &span,
2134                %error,
2135                "sending an error response to a pending request on a failed connection"
2136            );
2137            let _ = tx.send(Err(error.clone()));
2138        }
2139    }
2140}
2141
2142impl<S, Tx, C> Drop for Connection<S, Tx, C>
2143where
2144    Tx: Sink<Message, Error = SerializationError> + Unpin,
2145{
2146    fn drop(&mut self) {
2147        self.shutdown(PeerError::ConnectionDropped);
2148
2149        self.erase_state_metrics();
2150    }
2151}
2152
2153/// Map a list of inventory hashes to the corresponding unmined transaction IDs.
2154/// Non-transaction inventory hashes are skipped.
2155///
2156/// v4 transactions use a legacy transaction ID, and
2157/// v5 transactions use a witnessed transaction ID.
2158fn transaction_ids(items: &'_ [InventoryHash]) -> impl Iterator<Item = UnminedTxId> + '_ {
2159    items.iter().filter_map(InventoryHash::unmined_tx_id)
2160}
2161
2162/// Map a list of inventory hashes to the corresponding block hashes.
2163/// Non-block inventory hashes are skipped.
2164fn block_hashes(items: &'_ [InventoryHash]) -> impl Iterator<Item = block::Hash> + '_ {
2165    items.iter().filter_map(InventoryHash::block_hash)
2166}