zebra-network 17.0.0

Networking code for Zebra
Documentation
use std::{collections::HashSet, fmt, sync::Arc};

use zebra_chain::{
    block,
    transaction::{UnminedTx, UnminedTxId},
};

use super::super::types::Nonce;
use crate::{compact::CompactBlock, PeerSocketAddr};

#[cfg(any(test, feature = "proptest-impl"))]
use proptest_derive::Arbitrary;

/// A network request, represented in internal format.
///
/// The network layer aims to abstract away the details of the Bitcoin wire
/// protocol into a clear request/response API. Each [`Request`] documents the
/// possible [`Response`s](super::Response) it can generate; it is fine (and
/// recommended!) to match on the expected responses and treat the others as
/// `unreachable!()`, since their return indicates a bug in the network code.
///
/// # Cancellations
///
/// The peer set handles cancelled requests (i.e., requests where the future
/// returned by `Service::call` is dropped before it resolves) on a best-effort
/// basis. Requests are routed to a particular peer connection, and then
/// translated into Zcash protocol messages and sent over the network. If a
/// request is cancelled after it is submitted but before it is processed by a
/// peer connection, no messages will be sent. Otherwise, if it is cancelled
/// while waiting for a response, the peer connection resets its state and makes
/// a best-effort attempt to ignore any messages responsive to the cancelled
/// request, subject to limitations in the underlying Zcash protocol.
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
pub enum Request {
    /// Requests additional peers from the server.
    ///
    /// # Response
    ///
    /// Returns [`Response::Peers`](super::Response::Peers).
    Peers,

    /// Heartbeats triggered on peer connection start.
    ///
    /// This is included as a bit of a hack, it should only be used
    /// internally for connection management. You should not expect to
    /// be firing or handling `Ping` requests or `Pong` responses.
    #[doc(hidden)]
    Ping(Nonce),

    /// Request block data by block hashes.
    ///
    /// This uses a `HashSet` rather than a `Vec` for two reasons. First, it
    /// automatically deduplicates the requested blocks. Second, the internal
    /// protocol translator needs to maintain a `HashSet` anyways, in order to
    /// keep track of which requested blocks have been received and when the
    /// request is ready. Rather than force the internals to always convert into
    /// a `HashSet`, we require the caller to pass one, so that if the caller
    /// didn't start with a `Vec` but with, e.g., an iterator, they can collect
    /// directly into a `HashSet` and save work.
    ///
    /// Single-block requests prefer a connected peer that advertised the block. For blocks
    /// nobody advertised, they prefer peers that serve historic blocks. If no ready peer can
    /// serve the block but a busy peer might have it, the request waits for up to
    /// [`INVENTORY_BUSY_PEER_WAIT_TIMEOUT`](crate::constants::INVENTORY_BUSY_PEER_WAIT_TIMEOUT).
    /// Larger request sets use normal load balancing.
    ///
    /// The list contains zero or more block hashes.
    ///
    /// # Returns
    ///
    /// Returns [`Response::Blocks`](super::Response::Blocks), or
    /// [`Response::EarlyBlocks`](super::Response::EarlyBlocks) from a connection that negotiated
    /// compact block relay.
    BlocksByHash(HashSet<block::Hash>),

    /// Admits a screened compact advertisement to the ordinary bounded gossip downloader.
    ///
    /// Only the inbound connection creates this request, on connections that negotiated compact
    /// relay. Returns [`super::Response::Nil`] only when a new download was queued. Duplicate
    /// hashes, exhausted global capacity, and the per-IP cap return errors; no compact body may be
    /// retained.
    AdvertiseCompactBlock(block::Hash, Option<PeerSocketAddr>),

    /// Screens a compact header before retaining its body, without querying the mempool.
    ///
    /// Returns [`super::Response::Nil`] only for a valid next-tip candidate. Errors require
    /// ordinary full-block fallback, not peer punishment.
    #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
    CheckCompactHeader(Arc<CompactBlock>),

    /// Finds verified mempool candidates for a negotiated compact block.
    ///
    /// The inbound service screens the compact shape, proof of work, and current committed-tip
    /// header context before consulting the mempool.
    /// Returns [`super::Response::CompactBlockTransactions`].
    /// Errors mean full-block fallback, not peer punishment or block rejection.
    #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
    CompactBlockTransactions(Arc<CompactBlock>),

    /// Authenticates a reconstructed body against the current committed tip without caching it.
    ///
    /// Returns [`super::Response::Nil`] on success. Errors require full-block fallback and must
    /// not enter the block rejection cache. Success does not replace normal block verification.
    #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
    CheckCompactBlock(Arc<block::Block>),

    /// Download one block from a connected peer, waiting for eligible peer capacity.
    ///
    /// This outbound-only request is used by sync and gossip downloaders. Unlike
    /// [`Request::BlocksByHash`], temporary lack of capacity does not cause a local refusal.
    /// Callers must bound the entire readiness and response operation with a deadline.
    /// The peer's response timeout starts only when the request is dispatched.
    ///
    /// A known advertiser is preferred even if its advertisement was lost from the inventory
    /// registry. Missing-inventory reports, prior failures, and connection eligibility still apply.
    /// Without an eligible advertiser, routing prefers peers that serve historic blocks.
    ///
    /// The wire request is the same single-item `getdata` as [`Request::BlocksByHash`].
    /// Inbound `getdata` messages are always decoded as [`Request::BlocksByHash`], never this variant.
    ///
    /// # Returns
    ///
    /// Returns [`Response::Blocks`](super::Response::Blocks) containing the requested block,
    /// or [`Response::EarlyBlocks`](super::Response::EarlyBlocks) from a connection that
    /// negotiated compact block relay, or an error if the download fails.
    BlockDownload {
        /// The hash of the block to download.
        hash: block::Hash,
        /// A connected peer known to have advertised this block, if any.
        advertiser: Option<PeerSocketAddr>,
    },

    /// Request transactions by their unmined transaction ID.
    ///
    /// v4 transactions use a legacy transaction ID, and
    /// v5 transactions use a witnessed transaction ID.
    ///
    /// This uses a `HashSet` for the same reason as [`Request::BlocksByHash`].
    ///
    /// If this requests a recently-advertised transaction, the peer set will
    /// make a best-effort attempt to route the request to a peer that advertised
    /// the transaction. This routing is only used for request sets of size 1.
    /// Otherwise, it is routed using the normal load-balancing strategy.
    ///
    /// The list contains zero or more unmined transaction IDs.
    ///
    /// # Returns
    ///
    /// Returns [`Response::Transactions`](super::Response::Transactions).
    TransactionsById(HashSet<UnminedTxId>),

    /// Request block hashes of subsequent blocks in the chain, given hashes of
    /// known blocks.
    ///
    /// The known blocks list contains zero or more block hashes.
    ///
    /// # Returns
    ///
    /// Returns
    /// [`Response::BlockHashes`](super::Response::BlockHashes).
    ///
    /// # Warning
    ///
    /// This is implemented by sending a `getblocks` message. Bitcoin nodes
    /// respond to `getblocks` with an `inv` message containing a list of the
    /// subsequent blocks. However, Bitcoin nodes *also* send `inv` messages
    /// unsolicited in order to gossip new blocks to their peers. These gossip
    /// messages can race with the response to a `getblocks` request, and there
    /// is no way for the network layer to distinguish them. For this reason, the
    /// response may occasionally contain a single hash of a new chain tip rather
    /// than a list of hashes of subsequent blocks. We believe that unsolicited
    /// `inv` messages will always have exactly one block hash.
    FindBlocks {
        /// Hashes of known blocks, ordered from highest height to lowest height.
        //
        // TODO: make this into an IndexMap - an ordered unique list of hashes (#2244)
        known_blocks: Vec<block::Hash>,
        /// Optionally, the last block hash to request.
        stop: Option<block::Hash>,
    },

    /// Request headers of subsequent blocks in the chain, given hashes of
    /// known blocks.
    ///
    /// The known blocks list contains zero or more block hashes.
    ///
    /// # Returns
    ///
    /// Returns
    /// [`Response::BlockHeaders`](super::Response::BlockHeaders).
    FindHeaders {
        /// Hashes of known blocks, ordered from highest height to lowest height.
        //
        // TODO: make this into an IndexMap - an ordered unique list of hashes (#2244)
        known_blocks: Vec<block::Hash>,
        /// Optionally, the last header to request.
        stop: Option<block::Hash>,
    },

    /// Push an unmined transaction to a remote peer, without advertising it to them first.
    ///
    /// This is implemented by sending an unsolicited `tx` message.
    ///
    /// The second field is the address of the peer that pushed this `tx` to us:
    /// `Some(addr)` when a remote peer sent us the full transaction directly,
    /// and `None` when Zebra originates the push itself. Used by the mempool
    /// downloader to enforce a per-peer queue cap, mirroring
    /// [`Request::AdvertiseTransactionIds`]. See `GHSA-m9xx-8rcj-vmgp`.
    ///
    /// # Returns
    ///
    /// Returns [`Response::Nil`](super::Response::Nil).
    PushTransaction(UnminedTx, Option<PeerSocketAddr>),

    /// Advertise a set of unmined transactions to all peers.
    ///
    /// Both Zebra and zcashd sometimes advertise multiple transactions at once.
    ///
    /// This is implemented by sending an `inv` message containing the unmined
    /// transaction IDs, allowing the remote peer to choose whether to download
    /// them. Remote peers who choose to download the transaction will generate a
    /// [`Request::TransactionsById`] against the "inbound" service passed to
    /// [`init`](crate::init).
    ///
    /// v4 transactions use a legacy transaction ID, and
    /// v5 transactions use a witnessed transaction ID.
    ///
    /// The list contains zero or more transaction IDs.
    ///
    /// The peer set routes this request specially, sending it to *half of*
    /// the available peers.
    ///
    /// The second field is the address of the peer that sent us this `inv`:
    /// `Some(addr)` when the advertisement was relayed from a remote peer,
    /// and `None` when Zebra originates the advertisement itself (e.g. the
    /// mempool gossip task). Used by the mempool downloader to enforce a
    /// per-peer queue cap. See `GHSA-4fc2-h7jh-287c`.
    ///
    /// # Returns
    ///
    /// Returns [`Response::Nil`](super::Response::Nil).
    AdvertiseTransactionIds(HashSet<UnminedTxId>, Option<PeerSocketAddr>),

    /// Advertise a block to all peers.
    ///
    /// This is implemented by sending an `inv` message containing the
    /// block hash, allowing the remote peer to choose whether to download
    /// it. Remote peers who choose to download the block will generate a
    /// [`Request::BlocksByHash`] against the "inbound" service passed to
    /// [`init`](crate::init).
    ///
    /// Outbound block adverts use [`crate::BlockAdvertiser`], which samples peers and always
    /// includes configured sidecars independently of ordinary request readiness.
    ///
    /// The second field is the address of the peer that sent us this `inv`:
    /// `Some(addr)` when the advertisement was relayed from a remote peer,
    /// and `None` when Zebra originates the advertisement itself (for
    /// example from the sync gossip task). Consumers use the address to
    /// apply per-peer policies such as the inbound download per-IP cap.
    ///
    /// # Returns
    ///
    /// Outbound success acknowledges local writes to every selected peer, not remote receipt.
    /// Inbound handlers return [`Response::Nil`](super::Response::Nil) after accepting inventory.
    AdvertiseBlock(block::Hash, Option<PeerSocketAddr>),

    /// Advertise a block to every connected, non-banned peer.
    ///
    /// Use [`crate::BlockAdvertiser`], not the ordinary peer service. Each peer has a bounded
    /// advert channel; full or closed queues, revoked authorization, and write errors are failures.
    ///
    /// # Returns
    ///
    /// Returns [`Response::Nil`](super::Response::Nil) only after all selected local writes succeed.
    AdvertiseBlockToAll(block::Hash),

    /// Request the contents of this node's mempool.
    ///
    /// # Returns
    ///
    /// Returns [`Response::TransactionIds`](super::Response::TransactionIds).
    MempoolTransactionIds,

    /// Drive local peer-set maintenance without sending a request to a remote peer.
    ///
    /// The network-owned idle poller routes queued discovery and inventory requests when peers,
    /// deadlines, or cancellations change. Advert maintenance is acknowledged independently of
    /// ordinary readiness.
    ///
    /// Returns [`Response::Nil`](super::Response::Nil).
    #[cfg_attr(any(test, feature = "proptest-impl"), proptest(skip))]
    PollPeerSet,
}

impl fmt::Display for Request {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(&match self {
            Request::Peers => "Peers".to_string(),
            Request::Ping(_) => "Ping".to_string(),

            Request::BlocksByHash(hashes) => {
                format!("BlocksByHash({})", hashes.len())
            }
            Request::BlockDownload { .. } => "BlockDownload".to_string(),
            Request::AdvertiseCompactBlock(..) => "AdvertiseCompactBlock".to_string(),
            Request::CheckCompactHeader(_) => "CheckCompactHeader".to_string(),
            Request::CompactBlockTransactions(_) => "CompactBlockTransactions".to_string(),
            Request::CheckCompactBlock(_) => "CheckCompactBlock".to_string(),
            Request::TransactionsById(ids) => format!("TransactionsById({})", ids.len()),

            Request::FindBlocks { known_blocks, stop } => format!(
                "FindBlocks {{ known_blocks: {}, stop: {} }}",
                known_blocks.len(),
                if stop.is_some() { "Some" } else { "None" },
            ),
            Request::FindHeaders { known_blocks, stop } => format!(
                "FindHeaders {{ known_blocks: {}, stop: {} }}",
                known_blocks.len(),
                if stop.is_some() { "Some" } else { "None" },
            ),

            Request::PushTransaction(..) => "PushTransaction".to_string(),
            Request::AdvertiseTransactionIds(ids, _) => {
                format!("AdvertiseTransactionIds({})", ids.len())
            }

            Request::AdvertiseBlock(_, _) => "AdvertiseBlock".to_string(),
            Request::AdvertiseBlockToAll(_) => "AdvertiseBlockToAll".to_string(),
            Request::MempoolTransactionIds => "MempoolTransactionIds".to_string(),
            Request::PollPeerSet => "PollPeerSet".to_string(),
        })
    }
}

impl Request {
    /// Returns the Zebra internal request type as a string.
    pub fn command(&self) -> &'static str {
        match self {
            Request::Peers => "Peers",
            Request::Ping(_) => "Ping",

            Request::BlocksByHash(_) => "BlocksByHash",
            Request::BlockDownload { .. } => "BlockDownload",
            Request::AdvertiseCompactBlock(..) => "AdvertiseCompactBlock",
            Request::CheckCompactHeader(_) => "CheckCompactHeader",
            Request::CompactBlockTransactions(_) => "CompactBlockTransactions",
            Request::CheckCompactBlock(_) => "CheckCompactBlock",
            Request::TransactionsById(_) => "TransactionsById",

            Request::FindBlocks { .. } => "FindBlocks",
            Request::FindHeaders { .. } => "FindHeaders",

            Request::PushTransaction(..) => "PushTransaction",
            Request::AdvertiseTransactionIds(_, _) => "AdvertiseTransactionIds",

            Request::AdvertiseBlock(_, _) | Request::AdvertiseBlockToAll(_) => "AdvertiseBlock",
            Request::MempoolTransactionIds => "MempoolTransactionIds",
            Request::PollPeerSet => "PollPeerSet",
        }
    }

    /// Returns true if the request is for block or transaction inventory downloads.
    pub fn is_inventory_download(&self) -> bool {
        matches!(
            self,
            Request::BlockDownload { .. } | Request::BlocksByHash(_) | Request::TransactionsById(_)
        )
    }

    /// Returns the block hash inventory downloads from the request, if any.
    pub fn block_hash_inventory(&self) -> HashSet<block::Hash> {
        match self {
            Request::BlockDownload { hash, .. } => HashSet::from([*hash]),
            Request::BlocksByHash(block_hashes) => block_hashes.clone(),
            _ => HashSet::new(),
        }
    }

    /// Returns the transaction ID inventory downloads from the request, if any.
    pub fn transaction_id_inventory(&self) -> HashSet<UnminedTxId> {
        if let Request::TransactionsById(transaction_ids) = self {
            transaction_ids.clone()
        } else {
            HashSet::new()
        }
    }
}