Skip to main content

zebrad/components/
inbound.rs

1//! The inbound service handles requests from Zebra's peers.
2//!
3//! It downloads and verifies gossiped blocks and mempool transactions,
4//! when Zebra is close to the chain tip.
5//!
6//! It also responds to peer requests for blocks, transactions, and peer addresses.
7
8use std::{
9    collections::HashSet,
10    future::Future,
11    pin::Pin,
12    sync::Arc,
13    task::{Context, Poll},
14    time::Duration,
15};
16
17use futures::{
18    future::{FutureExt, TryFutureExt},
19    stream::Stream,
20};
21use tokio::sync::{
22    oneshot::{self, error::TryRecvError},
23    Semaphore,
24};
25use tower::{buffer::Buffer, timeout::Timeout, util::BoxService, Service, ServiceExt};
26
27use zebra_network::{self as zn, PeerSocketAddr};
28use zebra_state::{self as zs};
29
30use zebra_chain::{
31    block::{self, Block},
32    parameters::{Network, NetworkUpgrade},
33    serialization::ZcashSerialize,
34    transaction::UnminedTxId,
35    transparent,
36};
37use zebra_consensus::{router::RouterError, VerifyBlockError};
38use zebra_network::{
39    constants::GETDATA_MAX_BLOCK_COUNT, AddressBook, InventoryResponse, MAX_TX_INV_IN_SENT_MESSAGE,
40};
41use zebra_node_services::mempool;
42
43use crate::BoxError;
44
45// Re-use the syncer timeouts for consistency.
46use super::sync::BLOCK_VERIFY_TIMEOUT;
47
48use InventoryResponse::*;
49
50mod cached_peer_addr_response;
51pub(crate) mod downloads;
52
53use cached_peer_addr_response::CachedPeerAddrResponse;
54
55#[cfg(test)]
56mod tests;
57
58use downloads::{Downloads as BlockDownloads, HeightLimitError};
59
60/// The maximum amount of time an inbound service response can take.
61///
62/// If the response takes longer than this time, it will be cancelled,
63/// and the peer might be disconnected.
64pub const MAX_INBOUND_RESPONSE_TIME: Duration = Duration::from_secs(5);
65
66/// The number of bytes the [`Inbound`] service will queue in response to a single block or
67/// transaction request, before ignoring any additional block or transaction IDs in that request.
68///
69/// This is the same as `zcashd`'s default send buffer limit:
70/// <https://github.com/zcash/zcash/blob/829dd94f9d253bb705f9e194f13cb8ca8e545e1e/src/net.h#L84>
71/// as used in `ProcessGetData()`:
72/// <https://github.com/zcash/zcash/blob/829dd94f9d253bb705f9e194f13cb8ca8e545e1e/src/main.cpp#L6410-L6412>
73pub const GETDATA_SENT_BYTES_LIMIT: usize = 1_000_000;
74
75/// The maximum number of transaction IDs the [`Inbound`] service will look up in the mempool in
76/// response to a transaction request, before ignoring any additional transaction IDs in that
77/// request.
78///
79/// Derived from [`MAX_TX_INV_IN_SENT_MESSAGE`]: Zebra never advertises more transactions than
80/// that in a single `inv` message, so an honest peer following our advertisements never requests
81/// more than this in a single `getdata`. The wire format allows larger requests
82/// (`MAX_INV_IN_RECEIVED_MESSAGE` is 50,000), so the limit is taken from the protocol constant,
83/// not the message size.
84pub const GETDATA_MAX_TRANSACTION_COUNT: usize = MAX_TX_INV_IN_SENT_MESSAGE as usize;
85
86type BlockDownloadPeerSet =
87    Buffer<BoxService<zn::Request, zn::Response, zn::BoxError>, zn::Request>;
88type State = Buffer<BoxService<zs::Request, zs::Response, zs::BoxError>, zs::Request>;
89type Mempool = Buffer<BoxService<mempool::Request, mempool::Response, BoxError>, mempool::Request>;
90type SemanticBlockVerifier = Buffer<
91    BoxService<zebra_consensus::Request, block::Hash, RouterError>,
92    zebra_consensus::Request,
93>;
94type GossipedBlockDownloads =
95    BlockDownloads<BlockDownloadPeerSet, Timeout<SemanticBlockVerifier>, State, zs::LatestChainTip>;
96
97/// The services used by the [`Inbound`] service.
98pub struct InboundSetupData {
99    /// A shared list of peer addresses.
100    pub address_book: Arc<std::sync::Mutex<AddressBook>>,
101
102    /// A service that can be used to download gossiped blocks.
103    ///
104    /// Use [`zn::NetworkService::background_service`] so the inbound service does not keep
105    /// its own network alive.
106    pub block_download_peer_set: BlockDownloadPeerSet,
107
108    /// A service that verifies downloaded blocks.
109    ///
110    /// Given to `Inbound.block_downloads` after the required services are set up.
111    pub block_verifier: SemanticBlockVerifier,
112
113    /// A service that manages transactions in the memory pool.
114    pub mempool: Mempool,
115
116    /// A service that manages cached blockchain state.
117    pub state: State,
118
119    /// Allows efficient access to the best tip of the blockchain.
120    pub latest_chain_tip: zs::LatestChainTip,
121
122    /// A channel to send misbehavior reports to the [`AddressBook`].
123    pub misbehavior_sender: tokio::sync::mpsc::Sender<zn::MisbehaviorReport>,
124}
125
126/// Tracks the internal state of the [`Inbound`] service during setup.
127#[allow(clippy::large_enum_variant)]
128pub enum Setup {
129    /// Waiting for service setup to complete.
130    ///
131    /// All requests are ignored.
132    Pending {
133        // Configuration
134        //
135        /// The configured full verification concurrency limit.
136        full_verify_concurrency_limit: usize,
137
138        // Services
139        //
140        /// A oneshot channel used to receive required services,
141        /// after they are set up.
142        setup: oneshot::Receiver<InboundSetupData>,
143    },
144
145    /// Setup is complete.
146    ///
147    /// All requests are answered.
148    Initialized {
149        // Services
150        //
151        /// An owned partial list of peer addresses used as a `GetAddr` response, and
152        /// a shared list of peer addresses used to periodically refresh the partial list.
153        ///
154        /// Refreshed from the address book in `poll_ready` method
155        /// after [`CACHED_ADDRS_REFRESH_INTERVAL`](cached_peer_addr_response::CACHED_ADDRS_REFRESH_INTERVAL).
156        cached_peer_addr_response: CachedPeerAddrResponse,
157
158        /// A `futures::Stream` that downloads and verifies gossiped blocks.
159        block_downloads: Pin<Box<GossipedBlockDownloads>>,
160
161        /// A service that manages transactions in the memory pool.
162        mempool: Mempool,
163
164        /// A service that manages cached blockchain state.
165        state: State,
166
167        /// A channel to send misbehavior reports to the [`AddressBook`].
168        misbehavior_sender: tokio::sync::mpsc::Sender<zn::MisbehaviorReport>,
169    },
170
171    /// Temporary state used in the inbound service's internal initialization code.
172    ///
173    /// If this state occurs outside the service initialization code, the service panics.
174    FailedInit,
175
176    /// Setup failed, because the setup channel permanently failed.
177    /// The service keeps returning readiness errors for every request.
178    FailedRecv {
179        /// The original channel error.
180        error: SharedRecvError,
181    },
182}
183
184/// A wrapper around `Arc<TryRecvError>` that implements `Error`.
185#[derive(thiserror::Error, Debug, Clone)]
186#[error(transparent)]
187pub struct SharedRecvError(Arc<TryRecvError>);
188
189impl From<TryRecvError> for SharedRecvError {
190    fn from(source: TryRecvError) -> Self {
191        Self(Arc::new(source))
192    }
193}
194
195/// Uses the node state to respond to inbound peer requests.
196///
197/// This service, wrapped in appropriate middleware, is passed to
198/// `zebra_network::init` to respond to inbound peer requests.
199///
200/// The `Inbound` service is responsible for:
201///
202/// - supplying network data like peer addresses to other nodes;
203/// - supplying chain data like blocks to other nodes;
204/// - supplying mempool transactions to other nodes;
205/// - receiving gossiped transactions; and
206/// - receiving gossiped blocks.
207///
208/// Because the `Inbound` service is responsible for participating in the gossip
209/// protocols used for transaction and block diffusion, there is a potential
210/// overlap with the `ChainSync` and `Mempool` components.
211///
212/// The division of responsibility is that:
213///
214/// The `ChainSync` and `Mempool` components are *internally driven*,
215/// periodically polling the network to check for new blocks or transactions.
216///
217/// The `Inbound` service is *externally driven*, responding to block gossip
218/// by attempting to download and validate advertised blocks.
219///
220/// Gossiped transactions are forwarded to the mempool downloader,
221/// which unifies polled and gossiped transactions into a single download list.
222pub struct Inbound {
223    /// Provides service dependencies, if they are available.
224    ///
225    /// Some services are unavailable until Zebra has completed setup.
226    setup: Setup,
227
228    /// Read-only context for compact reconstruction; absent until explicitly configured.
229    compact_relay: Option<(Network, zs::ReadStateService)>,
230
231    /// Bounds mempool scans and detached blocking checks across all peer connections.
232    compact_checks: Arc<Semaphore>,
233}
234
235impl Inbound {
236    /// Create a new inbound service.
237    ///
238    /// Dependent services are sent via the `setup` channel after initialization.
239    pub fn new(
240        full_verify_concurrency_limit: usize,
241        setup: oneshot::Receiver<InboundSetupData>,
242    ) -> Inbound {
243        Inbound {
244            setup: Setup::Pending {
245                full_verify_concurrency_limit,
246                setup,
247            },
248            compact_relay: None,
249            compact_checks: Arc::new(Semaphore::new(3)),
250        }
251    }
252
253    /// Provides committed-tip context for negotiated compact block reconstruction, and for checking
254    /// the blocks of peers that negotiated compact block relay before their later validation
255    /// failures are exempt from scoring.
256    ///
257    /// The gossiped block downloader is created when the setup data arrives, so call this before
258    /// the service is polled.
259    pub fn with_compact_relay(mut self, network: Network, state: zs::ReadStateService) -> Self {
260        self.compact_relay = Some((network, state));
261        self
262    }
263
264    /// Remove `self.setup`, temporarily replacing it with an invalid state.
265    fn take_setup(&mut self) -> Setup {
266        let mut setup = Setup::FailedInit;
267        std::mem::swap(&mut self.setup, &mut setup);
268        setup
269    }
270}
271
272impl Service<zn::Request> for Inbound {
273    type Response = zn::Response;
274    type Error = zn::BoxError;
275    type Future =
276        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
277
278    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
279        // Check whether the setup is finished, but don't wait for it to
280        // become ready before reporting readiness. We expect to get it "soon",
281        // and reporting unreadiness might cause unwanted load-shedding, since
282        // the load-shed middleware is unable to distinguish being unready due
283        // to load from being unready while waiting on setup.
284
285        // Every setup variant handler must provide a result
286        let result;
287
288        self.setup = match self.take_setup() {
289            Setup::Pending {
290                full_verify_concurrency_limit,
291                mut setup,
292            } => match setup.try_recv() {
293                Ok(setup_data) => {
294                    let InboundSetupData {
295                        address_book,
296                        block_download_peer_set,
297                        block_verifier,
298                        mempool,
299                        state,
300                        latest_chain_tip,
301                        misbehavior_sender,
302                    } = setup_data;
303
304                    let cached_peer_addr_response = CachedPeerAddrResponse::new(address_book);
305
306                    let mut block_downloads = BlockDownloads::new(
307                        full_verify_concurrency_limit,
308                        block_download_peer_set,
309                        Timeout::new(block_verifier, BLOCK_VERIFY_TIMEOUT),
310                        state.clone(),
311                        latest_chain_tip,
312                    );
313                    if let Some((_, read_state)) = &self.compact_relay {
314                        block_downloads = block_downloads.with_read_state(read_state.clone());
315                    }
316                    let block_downloads = Box::pin(block_downloads);
317
318                    result = Ok(());
319                    Setup::Initialized {
320                        cached_peer_addr_response,
321                        block_downloads,
322                        mempool,
323                        state,
324                        misbehavior_sender,
325                    }
326                }
327                Err(TryRecvError::Empty) => {
328                    // There's no setup data yet, so keep waiting for it.
329                    //
330                    // We could use Future::poll() to get a waker and return Poll::Pending here.
331                    // But we want to drop excess requests during startup instead. Otherwise,
332                    // the inbound service gets overloaded, and starts disconnecting peers.
333                    result = Ok(());
334                    Setup::Pending {
335                        full_verify_concurrency_limit,
336                        setup,
337                    }
338                }
339                Err(error @ TryRecvError::Closed) => {
340                    // Mark the service as failed, because setup failed
341                    error!(?error, "inbound setup failed");
342                    let error: SharedRecvError = error.into();
343                    result = Err(error.clone().into());
344                    Setup::FailedRecv { error }
345                }
346            },
347            // Make sure previous setups were left in a valid state
348            Setup::FailedInit => unreachable!("incomplete previous Inbound initialization"),
349            // If setup failed, report service failure
350            Setup::FailedRecv { error } => {
351                result = Err(error.clone().into());
352                Setup::FailedRecv { error }
353            }
354            // Clean up completed download tasks, ignoring their results
355            Setup::Initialized {
356                cached_peer_addr_response,
357                mut block_downloads,
358                mempool,
359                state,
360                misbehavior_sender,
361            } => {
362                // # Correctness
363                //
364                // Clear the stream but ignore the final Pending return value.
365                // If we returned Pending here, and there were no waiting block downloads,
366                // then inbound requests would wait for the next block download, and hang forever.
367                while let Poll::Ready(Some(result)) = block_downloads.as_mut().poll_next(cx) {
368                    let Err((err, Some(advertiser_addr))) = result else {
369                        continue;
370                    };
371
372                    // # Security
373                    //
374                    // The gossiped block verifier is a `BlockVerifierRouter`, so a failed
375                    // verification is boxed as a `RouterError`. `Box<dyn Error>::downcast`
376                    // is an exact type match, so downcasting to `VerifyBlockError` alone
377                    // never matched, and misbehaving peers were never scored.
378                    // (`VerifyBlockError` only appears nested inside `RouterError::Block`.)
379                    //
380                    // `VerifyBlockError` is still handled, so scoring keeps working if the
381                    // verifier stack is ever rewired to skip the router.
382                    //
383                    // Any other error (a tower `Elapsed` timeout, a transport failure) is a
384                    // local problem rather than peer misbehavior, so it stays unscored.
385                    let score = if let Some(err) = err.downcast_ref::<RouterError>() {
386                        err.misbehavior_score()
387                    } else if let Some(err) = err.downcast_ref::<VerifyBlockError>() {
388                        err.misbehavior_score()
389                    } else if let Some(err) = err.downcast_ref::<HeightLimitError>() {
390                        // A gossiped block dropped before the verifier because its coinbase height
391                        // was outside the accepted range around the tip. The downloader only
392                        // attaches an advertiser address to these drops when the parent header
393                        // Zebra holds contradicts the claimed height, which proves the height was
394                        // rewritten (GHSA-4f6v-mj46-gxg3), so honest peers serving genuinely old or
395                        // far-ahead blocks are never scored.
396                        err.misbehavior_score()
397                    } else {
398                        continue;
399                    };
400
401                    if score != 0 {
402                        // Height limit drops are only attributed when the parent proves a rewrite.
403                        let reason = if err.is::<HeightLimitError>() {
404                            format!(
405                                "invalid gossiped block: parent header contradicts coinbase height: {err}"
406                            )
407                        } else {
408                            format!("invalid gossiped block: {err}")
409                        };
410                        let _ = misbehavior_sender.try_send(zn::MisbehaviorReport::new(
411                            advertiser_addr,
412                            score,
413                            reason,
414                        ));
415                    }
416                }
417
418                result = Ok(());
419
420                Setup::Initialized {
421                    cached_peer_addr_response,
422                    block_downloads,
423                    mempool,
424                    state,
425                    misbehavior_sender,
426                }
427            }
428        };
429
430        // Make sure we're leaving the setup in a valid state
431        if matches!(self.setup, Setup::FailedInit) {
432            unreachable!("incomplete Inbound initialization after poll_ready state handling");
433        }
434
435        // TODO:
436        //  * do we want to propagate backpressure from the download queue or its outbound network?
437        //    currently, the download queue waits for the outbound network in the download future,
438        //    and drops new requests after it reaches a hard-coded limit. This is the
439        //    "load shed directly" pattern from #1618.
440        //  * currently, the state service is always ready, unless its buffer is full.
441        //    So we might also want to propagate backpressure from its buffer.
442        //  * poll_ready needs to be implemented carefully, to avoid hangs or deadlocks.
443        //    See #1593 for details.
444        Poll::Ready(result)
445    }
446
447    /// Call the inbound service.
448    ///
449    /// Errors indicate that the peer has done something wrong or unexpected,
450    /// and will cause callers to disconnect from the remote peer.
451    #[instrument(name = "inbound", skip(self, req))]
452    fn call(&mut self, req: zn::Request) -> Self::Future {
453        let (cached_peer_addr_response, block_downloads, mempool, state) = match &mut self.setup {
454            Setup::Initialized {
455                cached_peer_addr_response,
456                block_downloads,
457                mempool,
458                state,
459                misbehavior_sender: _,
460            } => (cached_peer_addr_response, block_downloads, mempool, state),
461            _ => {
462                // A connection takes `Nil` for one of its compact relay requests as a passed
463                // check or an admitted download, so those requests fail until setup is done.
464                if matches!(
465                    req,
466                    zn::Request::CheckCompactHeader(_)
467                        | zn::Request::CompactBlockTransactions(_)
468                        | zn::Request::CheckCompactBlock(_)
469                        | zn::Request::AdvertiseCompactBlock(..)
470                ) {
471                    return async { Err("the inbound service is still starting".into()) }.boxed();
472                }
473
474                debug!("ignoring request from remote peer during setup");
475                return async { Ok(zn::Response::Nil) }.boxed();
476            }
477        };
478
479        match req {
480            req @ (zn::Request::CheckCompactHeader(_) | zn::Request::CompactBlockTransactions(_) | zn::Request::CheckCompactBlock(_)) => {
481                let Some((network, read_state)) = self.compact_relay.clone() else {
482                    return async { Err("compact relay context is unavailable".into()) }.boxed();
483                };
484                let mempool = mempool.clone();
485                let slots = self.compact_checks.clone();
486                tokio::time::timeout(
487                    MAX_INBOUND_RESPONSE_TIME,
488                    compact_request(req, network, read_state, mempool, slots),
489                ).map(|result| match result {
490                    Ok(response) => response,
491                    Err(error) => Err(error.into()),
492                }).boxed()
493            }
494            zn::Request::Peers => {
495                // # Security
496                //
497                // We truncate the list to not reveal our entire peer set in one call.
498                // But we don't monitor repeated requests and the results are shuffled,
499                // a crawler could just send repeated queries and get the full list.
500                //
501                // # Correctness
502                //
503                // If the address book is busy, try again inside the future. If it can't be locked
504                // twice, ignore the request.
505                cached_peer_addr_response.try_refresh();
506                let response = cached_peer_addr_response.value();
507
508                async move {
509                    Ok(response)
510                }.boxed()
511            }
512            zn::Request::BlocksByHash(hashes) => {
513                // We return an available or missing response to each inventory request,
514                // unless the request is empty, or it reaches a response limit.
515                if hashes.is_empty() {
516                    return async { Ok(zn::Response::Nil) }.boxed();
517                }
518
519                let state = state.clone();
520
521                async move {
522                    let mut blocks: Vec<InventoryResponse<(Arc<Block>, Option<PeerSocketAddr>), block::Hash>> = Vec::new();
523                    let mut total_size = 0;
524
525                    // Ignore any block hashes past the response limit.
526                    // This saves us expensive database lookups.
527                    for &hash in hashes.iter().take(GETDATA_MAX_BLOCK_COUNT) {
528                        // We check the limit after including at least one block, so that we can
529                        // send blocks greater than 1 MB (but only one at a time)
530                        if total_size >= GETDATA_SENT_BYTES_LIMIT {
531                            break;
532                        }
533
534                        let response = state.clone().ready().await?.call(zs::Request::Block(hash.into())).await?;
535
536                        // Add the block responses to the list, while updating the size limit.
537                        //
538                        // If there was a database error, return the error,
539                        // and stop processing further chunks.
540                        match response {
541                            zs::Response::Block(Some(block)) => {
542                                // If checking the serialized size of the block performs badly,
543                                // return the size from the state using a wrapper type.
544                                total_size += block.zcash_serialized_size();
545
546                                blocks.push(Available((block, None)))
547                            },
548                            // We don't need to limit the size of the missing block IDs list,
549                            // because it is already limited to the size of the getdata request
550                            // sent by the peer. (Their content and encodings are the same.)
551                            zs::Response::Block(None) => blocks.push(Missing(hash)),
552                            _ => unreachable!("wrong response from state"),
553                        }
554
555                    }
556
557                    // The network layer handles splitting this response into multiple `block`
558                    // messages, and a `notfound` message if needed.
559                    Ok(zn::Response::Blocks(blocks))
560                }.boxed()
561            }
562            zn::Request::TransactionsById(req_tx_ids) => {
563                // We return an available or missing response to each inventory request,
564                // unless the request is empty, or it reaches a response limit.
565                if req_tx_ids.is_empty() {
566                    return async { Ok(zn::Response::Nil) }.boxed();
567                }
568
569                // Ignore any transaction IDs past the request limit, before the mempool
570                // lookup, matching the block path above. This saves us mempool lookups,
571                // and bounds the `notfound` response size.
572                let req_tx_ids: HashSet<UnminedTxId> =
573                    if req_tx_ids.len() > GETDATA_MAX_TRANSACTION_COUNT {
574                        req_tx_ids
575                            .into_iter()
576                            .take(GETDATA_MAX_TRANSACTION_COUNT)
577                            .collect()
578                    } else {
579                        req_tx_ids
580                    };
581
582                let request = mempool::Request::TransactionsById(req_tx_ids.clone());
583                mempool.clone().oneshot(request).map_ok(move |resp| {
584                    let mut total_size = 0;
585
586                    let transactions = match resp {
587                        mempool::Response::Transactions(transactions) => transactions,
588                        _ => unreachable!("Mempool component should always respond to a `TransactionsById` request with a `Transactions` response"),
589                    };
590
591                    // Work out which transaction IDs were missing.
592                    let available_tx_ids: HashSet<UnminedTxId> = transactions.iter().map(|tx| tx.id).collect();
593                    // We don't need to limit the size of the missing transaction IDs list,
594                    // because it is already limited to `GETDATA_MAX_TRANSACTION_COUNT` by
595                    // the cap above.
596                    let missing = req_tx_ids.into_iter().filter(|tx_id| !available_tx_ids.contains(tx_id)).map(Missing);
597
598                    // If we skip sending some transactions because the limit has been reached,
599                    // they aren't reported as missing. This matches `zcashd`'s behaviour:
600                    // <https://github.com/zcash/zcash/blob/829dd94f9d253bb705f9e194f13cb8ca8e545e1e/src/main.cpp#L6410-L6412>
601                    let available = transactions.into_iter().take_while(|tx| {
602                        // We check the limit after including the transaction,
603                        // so that we can send transactions greater than 1 MB
604                        // (but only one at a time)
605                        let within_limit = total_size < GETDATA_SENT_BYTES_LIMIT;
606
607                        total_size += tx.size;
608
609                        within_limit
610                    }).map(|tx| Available((tx, None)));
611
612                    // The network layer handles splitting this response into multiple `tx`
613                    // messages, and a `notfound` message if needed.
614                    zn::Response::Transactions(available.chain(missing).collect())
615                }).boxed()
616            }
617            // Find* responses are already size-limited by the state.
618            zn::Request::FindBlocks { known_blocks, stop } => {
619                let request = zs::Request::FindBlockHashes { known_blocks, stop };
620                state.clone().oneshot(request).map_ok(|resp| match resp {
621                    zs::Response::BlockHashes(hashes) if hashes.is_empty() => zn::Response::Nil,
622                    zs::Response::BlockHashes(hashes) => zn::Response::BlockHashes(hashes),
623                    _ => unreachable!("zebra-state should always respond to a `FindBlockHashes` request with a `BlockHashes` response"),
624                })
625                    .boxed()
626            }
627            zn::Request::FindHeaders { known_blocks, stop } => {
628                let request = zs::Request::FindBlockHeaders { known_blocks, stop };
629                state.clone().oneshot(request).map_ok(|resp| match resp {
630                    // Always reply with a `headers` message, even when empty: the
631                    // `getheaders` protocol requires a `headers` response, and
632                    // returning `Nil` (which sends nothing) leaves a peer's
633                    // `getheaders` request pending forever. A zcashd sidecar
634                    // following Zebra defers every later inv-triggered
635                    // `getheaders` behind that stuck request and never syncs.
636                    zs::Response::BlockHeaders(headers) => zn::Response::BlockHeaders(headers),
637                    _ => unreachable!("zebra-state should always respond to a `FindBlockHeaders` request with a `BlockHeaders` response"),
638                })
639                    .boxed()
640            }
641            zn::Request::PushTransaction(transaction, sender) => {
642                // Tag a directly pushed transaction with the sending peer so the
643                // mempool downloader can enforce a per-peer queue cap, mirroring
644                // the advertisement path below. See `GHSA-m9xx-8rcj-vmgp`.
645                let request = match sender {
646                    Some(peer_addr) => mempool::Request::QueueFromPeer {
647                        candidates: vec![transaction.into()],
648                        source: *peer_addr,
649                    },
650                    None => mempool::Request::Queue(vec![transaction.into()]),
651                };
652                mempool
653                    .clone()
654                    .oneshot(request)
655                    // The response just indicates if processing was queued or not; ignore it
656                    .map_ok(|_resp| zn::Response::Nil)
657                    .boxed()
658            }
659            zn::Request::AdvertiseTransactionIds(transactions, advertiser) => {
660                // Tag the advertised txids with the announcing peer so the
661                // mempool downloader can enforce a per-peer queue cap.
662                // See `GHSA-4fc2-h7jh-287c`.
663                let request = match advertiser {
664                    Some(peer_addr) => mempool::Request::QueueFromPeer {
665                        candidates: transactions.into_iter().map(Into::into).collect(),
666                        source: *peer_addr,
667                    },
668                    None => mempool::Request::Queue(
669                        transactions.into_iter().map(Into::into).collect(),
670                    ),
671                };
672                mempool
673                    .clone()
674                    .oneshot(request)
675                    // The response just indicates if processing was queued or not; ignore it
676                    .map_ok(|_resp| zn::Response::Nil)
677                    .boxed()
678            }
679            zn::Request::AdvertiseCompactBlock(hash, advertiser) => {
680                let admitted = matches!(
681                    block_downloads.download_and_verify(hash, advertiser),
682                    downloads::DownloadAction::AddedToQueue
683                );
684                async move {
685                    if admitted {
686                        Ok(zn::Response::Nil)
687                    } else {
688                        Err("compact advertisement was not admitted".into())
689                    }
690                }.boxed()
691            }
692            zn::Request::AdvertiseBlock(hash, advertiser) => {
693                block_downloads.download_and_verify(hash, advertiser);
694                async { Ok(zn::Response::Nil) }.boxed()
695            }
696            // The size of this response is limited by the `Connection` state machine in the network layer
697            zn::Request::MempoolTransactionIds => {
698                mempool.clone().oneshot(mempool::Request::TransactionIds).map_ok(|resp| match resp {
699                    mempool::Response::TransactionIds(transaction_ids) => zn::Response::TransactionIds(transaction_ids.into_iter().collect()),
700                    _ => unreachable!("Mempool component should always respond to a `TransactionIds` request with a `TransactionIds` response"),
701                })
702                    .boxed()
703            }
704            zn::Request::Ping(_) => {
705                unreachable!("ping requests are handled internally");
706            }
707
708            zn::Request::AdvertiseBlockToAll(_) => unreachable!("should always be decoded as `AdvertiseBlock` request"),
709
710            zn::Request::BlockDownload { .. } => unreachable!("peers never send outbound block downloads"),
711
712            zn::Request::PollPeerSet => unreachable!("peers never send peer set poll requests"),
713        }
714    }
715}
716
717/// Screens compact requests without publishing bodies or caching probabilistic failure verdicts.
718async fn compact_request(
719    req: zn::Request,
720    network: Network,
721    read_state: zs::ReadStateService,
722    mempool: Mempool,
723    slots: Arc<Semaphore>,
724) -> Result<zn::Response, BoxError> {
725    let header_only = matches!(req, zn::Request::CheckCompactHeader(_));
726    // Header screening runs for every peer's announcement, so it fails fast when the checks are
727    // busy. The later checks only run for a block that the block downloader admitted, so they
728    // wait for a permit, and get one before any new screening does.
729    let permit = Arc::new(if header_only {
730        slots.try_acquire_owned()?
731    } else {
732        slots.acquire_owned().await?
733    });
734    match req {
735        zn::Request::CheckCompactHeader(compact)
736        | zn::Request::CompactBlockTransactions(compact) => {
737            let checked = compact.clone();
738            let worker_permit = permit.clone();
739            let height = tokio::task::spawn_blocking(move || {
740                let _permit = worker_permit;
741                screen_compact_header(&checked, &network)
742            })
743            .await??;
744            let response = read_state
745                .oneshot(zs::ReadRequest::CheckBestTipHeader {
746                    header: compact.header.clone(),
747                    height,
748                })
749                .await?;
750            assert!(matches!(response, zs::ReadResponse::ValidBestTipHeader));
751            if header_only {
752                return Ok(zn::Response::Nil);
753            }
754            if compact.short_ids.is_empty() {
755                return Ok(zn::Response::CompactBlockTransactions(Vec::new()));
756            }
757            // Boxed: without type erasure the inbound response future fails a higher-ranked
758            // lifetime check on the error type.
759            let mempool::Response::TransactionIds(ids) = mempool
760                .clone()
761                .oneshot(mempool::Request::TransactionIds)
762                .boxed()
763                .await?
764            else {
765                unreachable!("transaction ID requests return transaction IDs");
766            };
767            let worker_permit = permit.clone();
768            let ids = tokio::task::spawn_blocking(move || {
769                let _permit = worker_permit;
770                compact.matching_ids(ids)
771            })
772            .await?;
773            let mempool::Response::Transactions(transactions) = mempool
774                .oneshot(mempool::Request::TransactionsById(ids))
775                .boxed()
776                .await?
777            else {
778                unreachable!("exact transaction lookups return transactions");
779            };
780            let bytes = transactions
781                .iter()
782                .fold(0usize, |bytes, tx| bytes.saturating_add(tx.size));
783            if u64::try_from(bytes).unwrap_or(u64::MAX) > block::MAX_BLOCK_BYTES {
784                return Err("compact candidates exceed the block byte limit".into());
785            }
786            Ok(zn::Response::CompactBlockTransactions(transactions))
787        }
788        zn::Request::CheckCompactBlock(block) => {
789            let checked = block.clone();
790            let worker_permit = permit.clone();
791            tokio::task::spawn_blocking(move || {
792                let _permit = worker_permit;
793                if u64::try_from(checked.zcash_serialized_size()).unwrap_or(u64::MAX)
794                    > block::MAX_BLOCK_BYTES
795                {
796                    return Err("compact body exceeds the block byte limit".into());
797                }
798                zebra_consensus::coinbase_is_first(&checked)?;
799                let hashes = checked
800                    .transactions
801                    .iter()
802                    .map(|tx| tx.hash())
803                    .collect::<Vec<_>>();
804                zebra_consensus::merkle_root_validity(&network, &checked, &hashes)?;
805                Ok::<_, BoxError>(())
806            })
807            .await??;
808            let response = read_state
809                .oneshot(zs::ReadRequest::CheckBestTipBlockCommitments(block))
810                .await?;
811            assert!(matches!(
812                response,
813                zs::ReadResponse::ValidBestTipBlockCommitments
814            ));
815            Ok(zn::Response::Nil)
816        }
817        _ => unreachable!("only compact requests enter compact screening"),
818    }
819}
820
821/// Rejects malformed or unauthenticated headers before exposing local mempool membership.
822fn screen_compact_header(
823    compact: &zn::compact::CompactBlock,
824    network: &Network,
825) -> Result<block::Height, BoxError> {
826    compact.validate()?;
827    let height = compact.prefilled[0]
828        .1
829        .inputs()
830        .into_iter()
831        .next()
832        .and_then(|input| match input {
833            transparent::Input::Coinbase { height, .. } => Some(height),
834            _ => None,
835        })
836        .ok_or("compact coinbase has no height")?;
837    if NetworkUpgrade::current(network, height) < NetworkUpgrade::Nu5 {
838        return Err("compact authentication requires NU5 commitments".into());
839    }
840    let hash = compact.block_hash();
841    let header = &compact.header;
842    header.time_is_valid_at(chrono::Utc::now(), &height, &hash)?;
843    if network.disable_pow() {
844        zebra_consensus::difficulty_threshold_is_valid(header, network, &height, &hash)?;
845    } else {
846        zebra_consensus::difficulty_is_valid(header, network, &height, &hash)?;
847        zebra_consensus::equihash_solution_is_valid(header)?;
848    }
849    Ok(height)
850}