Skip to main content

zebra_network/peer/connection/
compact_relay.rs

1//! Opt-in compact block transport for committed blocks.
2//!
3//! A negotiated peer announces a new block as its header, short transaction IDs and coinbase.
4//! The receiver rebuilds the block from its mempool, asks once for the transactions it is missing,
5//! and falls back to an ordinary `getdata` on any problem. Consensus checks and source scoring
6//! remain in the ordinary downloader.
7
8use std::{
9    collections::{HashSet, VecDeque},
10    sync::{Arc, LazyLock},
11    time::Duration,
12};
13
14use futures::Sink;
15use tokio::{
16    sync::{OwnedSemaphorePermit, Semaphore},
17    time::{sleep, sleep_until, timeout_at, Instant, Sleep},
18};
19use tower::{Service, ServiceExt};
20use zebra_chain::{
21    block::{self, Block, MAX_BLOCK_BYTES},
22    chain_tip::ChainTip,
23    serialization::{CompactSizeMessage, FakeWriter, SerializationError, ZcashSerialize},
24};
25
26use super::{Connection, Handler, InventoryResponse, State};
27use crate::{
28    compact::{BlockTransactions, BlockTransactionsRequest, CompactBlock, Reconstruction},
29    constants,
30    peer_set::InventoryChange,
31    protocol::external::{InventoryHash, Message},
32    BoxError, PeerError, Request, Response,
33};
34
35// A decoded body can retain substantially more memory than its two-megabyte wire encoding.
36// Global slots bound the bodies kept across all connections, including detached hash work.
37// Without a free slot, blocks are announced or downloaded in full.
38//
39// Announced blocks and peers' bodies have separate slots, so connections that hold the
40// announcements of this node's blocks can't stop it receiving compact blocks, or the other way
41// around.
42//
43// Announced blocks are committed blocks, which the state also holds.
44pub(super) static SENT_SLOTS: LazyLock<Arc<Semaphore>> =
45    LazyLock::new(|| Arc::new(Semaphore::new(6)));
46// Received bodies must pass proof-of-work and current-best-tip screening, and then win the block
47// downloader's admission for their hash, before they keep a slot. A rebuilt block keeps the slot
48// of the body it was built from. A connection keeps at most one received body and one rebuilt
49// block, and one announced block.
50pub(super) static RECEIVED_SLOTS: LazyLock<Arc<Semaphore>> =
51    LazyLock::new(|| Arc::new(Semaphore::new(6)));
52const RETENTION: Duration = Duration::from_secs(15);
53/// The number of blocks a connection remembers its peer announcing in compact form.
54const ANNOUNCED_BLOCKS: usize = 4;
55const RECOVERY_TIMEOUT: Duration = Duration::from_secs(2);
56
57/// The number of transaction recovery requests answered for each delivered announcement.
58///
59/// A Zebra recipient asks once for each announcement, so the second reply allows one repeat.
60pub(super) const MAX_RECOVERY_REPLIES: usize = 2;
61
62struct ServingBlock {
63    block: Arc<Block>,
64    /// Keep the sent short-ID keys reproducible without retaining the compact transaction vectors.
65    nonce: u64,
66}
67
68#[derive(Default)]
69pub(super) struct CompactRelay {
70    pub(super) send: bool,
71    received: Option<(Arc<CompactBlock>, Instant, OwnedSemaphorePermit)>,
72    sent: Option<(ServingBlock, Option<Instant>, OwnedSemaphorePermit)>,
73    /// Bound aggregate recovery payloads, including repeated requests.
74    recovery_bytes_left: usize,
75    /// Bound the number of recovery replies for each delivered announcement. The byte budget
76    /// bounds their size, not their number.
77    recovery_replies_left: usize,
78    /// Gossip and sync can request the same body before either verifier commits it.
79    reconstructed: Option<(Arc<Block>, Instant, OwnedSemaphorePermit)>,
80    last_received: Option<Instant>,
81    /// The deadline of the block download that this connection has just started, for the
82    /// request timer.
83    download_deadline: Option<Instant>,
84    /// The blocks that the peer announced in compact form most recently, whether or not this
85    /// connection kept them.
86    announced: VecDeque<block::Hash>,
87}
88
89impl CompactRelay {
90    pub(super) fn clear_sent(&mut self) {
91        self.sent = None;
92    }
93
94    /// Drops every body this connection keeps, which releases their global slots.
95    pub(super) fn release(&mut self) {
96        self.received = None;
97        self.sent = None;
98        self.reconstructed = None;
99    }
100
101    /// Returns the deadline of the block download that this connection has just started.
102    pub(super) fn take_download_deadline(&mut self) -> Option<Instant> {
103        self.download_deadline.take()
104    }
105
106    /// Returns true if this peer's compact announcement can answer a download of `hash`.
107    pub(super) fn is_cached(&self, hash: block::Hash) -> bool {
108        self.received
109            .as_ref()
110            .is_some_and(|(block, _, _)| block.header.hash() == hash)
111            || self
112                .reconstructed
113                .as_ref()
114                .is_some_and(|(block, _, _)| block.hash() == hash)
115    }
116
117    /// Records that the peer announced the block `hash` in compact form.
118    fn note_announced(&mut self, hash: block::Hash) {
119        if self.announced.contains(&hash) {
120            return;
121        }
122        if self.announced.len() == ANNOUNCED_BLOCKS {
123            self.announced.pop_front();
124        }
125        self.announced.push_back(hash);
126    }
127
128    /// Returns true if the peer announced the block `hash` in compact form recently, so it
129    /// already has that block.
130    fn has_announced(&self, hash: block::Hash) -> bool {
131        self.announced.contains(&hash) || self.is_cached(hash)
132    }
133
134    pub(super) fn mark_sent(&mut self) {
135        let (_, until, _) = self
136            .sent
137            .as_mut()
138            .expect("a delivered compact announcement retains its serving snapshot");
139        *until = Some(Instant::now() + RETENTION);
140        self.recovery_bytes_left =
141            usize::try_from(MAX_BLOCK_BYTES).expect("the block byte limit fits in memory");
142        self.recovery_replies_left = MAX_RECOVERY_REPLIES;
143    }
144
145    pub(super) fn expire(&mut self) {
146        let now = Instant::now();
147        if self
148            .received
149            .as_ref()
150            .is_some_and(|(_, until, _)| *until <= now)
151        {
152            self.received = None;
153        }
154        if self
155            .sent
156            .as_ref()
157            .is_some_and(|(_, until, _)| until.is_some_and(|until| until <= now))
158        {
159            self.sent = None;
160        }
161        if self
162            .reconstructed
163            .as_ref()
164            .is_some_and(|(_, until, _)| *until <= now)
165        {
166            self.reconstructed = None;
167        }
168    }
169
170    pub(super) fn has_cached(&self) -> bool {
171        self.received.is_some() || self.sent.is_some() || self.reconstructed.is_some()
172    }
173
174    pub(super) fn expiry(&self) -> Instant {
175        self.received
176            .as_ref()
177            .map(|(_, until, _)| *until)
178            .into_iter()
179            .chain(self.sent.as_ref().and_then(|(_, until, _)| *until))
180            .chain(self.reconstructed.as_ref().map(|(_, until, _)| *until))
181            .min()
182            .unwrap_or_else(|| Instant::now() + RETENTION)
183    }
184}
185
186impl<S, Tx, C> Connection<S, Tx, C>
187where
188    S: Service<Request, Response = Response, Error = BoxError>,
189    C: ChainTip,
190    Tx: Sink<Message, Error = SerializationError> + Unpin,
191{
192    /// Query the existing bounded inbound service without turning collision recovery into scoring.
193    async fn compact_query(&mut self, request: Request) -> Option<Response> {
194        self.compact_query_until(request, Instant::now() + constants::REQUEST_TIMEOUT)
195            .await
196    }
197
198    /// Like [`Self::compact_query`], but gives up at `deadline`.
199    async fn compact_query_until(
200        &mut self,
201        request: Request,
202        deadline: Instant,
203    ) -> Option<Response> {
204        timeout_at(deadline, async {
205            self.svc.ready().await.ok()?.call(request).await.ok()
206        })
207        .await
208        .ok()
209        .flatten()
210    }
211
212    /// Recheck this peer's authorization after sink readiness, as ordinary requests do.
213    ///
214    /// The write stops at `deadline`, the deadline of the block download that it is part of.
215    async fn send_compact_request(
216        &mut self,
217        message: Message,
218        deadline: Instant,
219    ) -> Result<(), PeerError> {
220        let address = self.connection_info.connected_addr.get_transient_addr();
221        let version = self.connection_info.remote.version;
222        let minimum = &mut self.minimum_peer_version;
223        let bans = &self.bans_receiver;
224        let send = self.peer_tx.send_authorized(message, || {
225            if version < minimum.current()
226                || address.is_some_and(|addr| bans.borrow().is_banned(addr.ip()))
227            {
228                Err(PeerError::ConnectionDropped)
229            } else {
230                Ok(())
231            }
232        });
233
234        // A write that is cut off can leave part of a message in the sink. So this fails the
235        // connection, like the usual send timeout does.
236        timeout_at(deadline, send)
237            .await
238            .map_err(|_| PeerError::ConnectionSendTimeout)?
239    }
240
241    /// Returns an error if the peer is now banned, or below the minimum version.
242    ///
243    /// Requests are checked like this right before they are written, so a response that needs no
244    /// write is checked before it is returned.
245    fn live_authorization(&mut self) -> Result<(), PeerError> {
246        let address = self.connection_info.connected_addr.get_transient_addr();
247        if self.connection_info.remote.version < self.minimum_peer_version.current()
248            || address.is_some_and(|addr| self.bans_receiver.borrow().is_banned(addr.ip()))
249        {
250            Err(PeerError::ConnectionDropped)
251        } else {
252            Ok(())
253        }
254    }
255
256    /// Fetch the committed block before constructing an announcement.
257    async fn compact_serving_block(&mut self, hash: block::Hash) -> Option<ServingBlock> {
258        let Response::Blocks(blocks) = self
259            .compact_query(Request::BlocksByHash(HashSet::from([hash])))
260            .await?
261        else {
262            return None;
263        };
264        let block = blocks.into_iter().find_map(|item| match item {
265            InventoryResponse::Available((block, _)) if block.hash() == hash => Some(block),
266            _ => None,
267        })?;
268        Some(ServingBlock {
269            block,
270            nonce: rand::random(),
271        })
272    }
273
274    pub(super) async fn compact_advert(&mut self, hash: block::Hash) -> Option<Message> {
275        if !self.connection_info.early_block_relay || !self.compact.send {
276            return None;
277        }
278        self.compact.expire();
279        // The peer announced this block to this node, so it gets the block inventory, as it would
280        // without compact relay.
281        if self.compact.has_announced(hash) {
282            return None;
283        }
284        // Do not replace a body while the peer can still be recovering its transactions.
285        if self.compact.sent.is_some() {
286            return None;
287        }
288        let permit = SENT_SLOTS.clone().try_acquire_owned().ok()?;
289        let serving = self.compact_serving_block(hash).await?;
290        let (serving, compact, permit) = tokio::task::spawn_blocking(move || {
291            let compact = CompactBlock::from_block(&serving.block, serving.nonce)
292                .ok()
293                .and_then(|compact| smaller_announcement(compact, &serving.block));
294            (serving, compact, permit)
295        })
296        .await
297        .ok()?;
298        let compact = compact?;
299        self.compact.sent = Some((serving, None, permit));
300        Some(Message::CompactBlock(Arc::new(compact)))
301    }
302
303    pub(super) async fn receive_compact(&mut self, block: Arc<CompactBlock>) {
304        if !self.connection_info.early_block_relay {
305            return;
306        }
307        self.compact.expire();
308        let hash = block.header.hash();
309        self.compact.note_announced(hash);
310        let advertiser = self.connection_info.connected_addr.get_transient_addr();
311        if self.compact.received.is_none()
312            && self
313                .compact
314                .last_received
315                .is_none_or(|last| last.elapsed() >= RETENTION)
316            && matches!(
317                self.compact_query(Request::CheckCompactHeader(block.clone()))
318                    .await,
319                Some(Response::Nil)
320            )
321        {
322            if let Ok(permit) = RECEIVED_SLOTS.clone().try_acquire_owned() {
323                // The peer has this screened block, even if the downloader takes it from another
324                // peer, or doesn't take it now.
325                self.register_compact_announcement(hash);
326                if matches!(
327                    self.compact_query(Request::AdvertiseCompactBlock(hash, advertiser))
328                        .await,
329                    Some(Response::Nil)
330                ) {
331                    metrics::counter!("zebra.net.compact_block.admitted").increment(1);
332                    self.compact.last_received = Some(Instant::now());
333                    self.compact.received = Some((block, Instant::now() + RETENTION, permit));
334                }
335                return;
336            }
337        }
338        // Reconstruction starts only after the downloader applies its global/per-IP admission.
339        self.register_compact_announcement(hash);
340        self.drive_peer_request(Request::AdvertiseBlock(hash, advertiser))
341            .await;
342    }
343
344    /// Tells the peer set that this peer has the block it announced, like a block inventory does,
345    /// so downloads of the block without a source can be sent to this peer.
346    ///
347    /// A compact announcement replaces the block inventory, and this is only called once the
348    /// announcement is screened, or handled like an inventory.
349    fn register_compact_announcement(&self, hash: block::Hash) {
350        if let (Some(inventory), Some(advertiser)) = (
351            &self.compact_inventory,
352            self.connection_info.connected_addr.get_transient_addr(),
353        ) {
354            let _ = inventory.send(InventoryChange::new_available(
355                InventoryHash::Block(hash),
356                advertiser,
357            ));
358        }
359    }
360
361    pub(super) async fn download_block(&mut self, hash: block::Hash) -> Result<Handler, PeerError> {
362        // The whole download, including a fallback to the full block, has one request timeout.
363        let deadline = Instant::now() + constants::REQUEST_TIMEOUT;
364        self.compact.download_deadline = Some(deadline);
365        self.compact.expire();
366        let cached = self
367            .compact
368            .reconstructed
369            .as_ref()
370            .map(|(block, _, _)| block)
371            .filter(|block| block.hash() == hash)
372            .cloned();
373        if let Some(block) = cached {
374            return self.compact_response(block);
375        }
376        if self
377            .compact
378            .received
379            .as_ref()
380            .is_some_and(|(block, _, _)| block.header.hash() == hash)
381        {
382            let (compact, _, permit) = self
383                .compact
384                .received
385                .take()
386                .expect("the matching cached compact block exists");
387            if let Some(Response::CompactBlockTransactions(candidates)) = self
388                .compact_query_until(Request::CompactBlockTransactions(compact.clone()), deadline)
389                .await
390            {
391                let result =
392                    tokio::task::spawn_blocking(move || (compact.reconstruct(candidates), permit))
393                        .await;
394                if let Ok((Ok(reconstruction), permit)) = result {
395                    let indexes = reconstruction.missing_indexes();
396                    if indexes.is_empty() {
397                        if let Some(block) = self
398                            .finish_compact(
399                                reconstruction,
400                                BlockTransactions {
401                                    block_hash: hash,
402                                    transactions: Vec::new(),
403                                },
404                                permit,
405                                deadline,
406                            )
407                            .await
408                        {
409                            return self.compact_response(block);
410                        }
411                    } else if indexes.len() < reconstruction.transaction_count().div_ceil(2) {
412                        // Recovering most of a block costs about as much as downloading it, and
413                        // a recovery that misses its short timeout is downloaded again in full.
414                        // So when at least half the transactions are missing, this downloads
415                        // the full block straight away.
416                        self.send_compact_request(
417                            Message::GetBlockTransactions(BlockTransactionsRequest {
418                                block_hash: hash,
419                                indexes,
420                            }),
421                            deadline,
422                        )
423                        .await?;
424                        return Ok(Handler::CompactBlock {
425                            reconstruction,
426                            permit,
427                            deadline,
428                        });
429                    }
430                }
431            }
432        }
433        self.send_compact_request(Message::GetData(vec![hash.into()]), deadline)
434            .await?;
435        Ok(Handler::BlocksByHash {
436            pending_hashes: HashSet::from([hash]),
437            blocks: Vec::with_capacity(1),
438        })
439    }
440
441    /// Returns a block rebuilt from the peer's compact announcement, if the peer is still eligible.
442    ///
443    /// Rebuilding waits for the inbound service, so the peer can be banned, or fall below the
444    /// minimum version, before the block is ready.
445    fn compact_response(&mut self, block: Arc<Block>) -> Result<Handler, PeerError> {
446        self.live_authorization()?;
447        Ok(Handler::Finished(Ok(Response::Blocks(vec![
448            InventoryResponse::Available((
449                block,
450                self.connection_info.connected_addr.get_transient_addr(),
451            )),
452        ]))))
453    }
454
455    async fn finish_compact(
456        &mut self,
457        reconstruction: Reconstruction,
458        response: BlockTransactions,
459        permit: OwnedSemaphorePermit,
460        deadline: Instant,
461    ) -> Option<Arc<Block>> {
462        let (block, permit) =
463            tokio::task::spawn_blocking(move || (reconstruction.finish(response), permit))
464                .await
465                .ok()?;
466        let block = block.ok()?;
467        // A txid Merkle root does not bind v5/v6 proofs or signatures. Authenticate the ordered
468        // authorization root before giving these probabilistically reconstructed bytes to consensus.
469        if !matches!(
470            self.compact_query_until(Request::CheckCompactBlock(block.clone()), deadline)
471                .await,
472            Some(Response::Nil)
473        ) {
474            return None;
475        }
476        metrics::counter!("zebra.net.compact_block.rebuilt").increment(1);
477        self.compact.reconstructed = Some((block.clone(), Instant::now() + RETENTION, permit));
478        Some(block)
479    }
480
481    pub(super) async fn receive_compact_transactions(&mut self, response: BlockTransactions) {
482        let hash = response.block_hash;
483        let State::AwaitingResponse { handler, .. } = &mut self.state else {
484            return;
485        };
486        if !matches!(handler, Handler::CompactBlock { reconstruction, .. } if reconstruction.block_hash() == hash)
487        {
488            return;
489        }
490        if let Some(recovery) = &self.compact_recovery {
491            recovery.send_replace(None);
492        }
493        let Handler::CompactBlock {
494            reconstruction,
495            permit,
496            deadline,
497        } = std::mem::replace(handler, Handler::Finished(Ok(Response::Nil)))
498        else {
499            unreachable!("the matching reconstruction was checked")
500        };
501        if let Some(block) = self
502            .finish_compact(reconstruction, response, permit, deadline)
503            .await
504        {
505            match self.compact_response(block) {
506                Ok(response) => {
507                    if let State::AwaitingResponse { handler, .. } = &mut self.state {
508                        *handler = response;
509                    }
510                }
511                // Failing the connection also fails the waiting request.
512                Err(error) => self.fail_with(error).await,
513            }
514        } else {
515            self.fallback_compact(hash, deadline).await;
516        }
517    }
518
519    /// Downloads the full block, by the deadline of the compact download it replaces.
520    pub(super) async fn fallback_compact(&mut self, hash: block::Hash, deadline: Instant) {
521        self.clear_compact_recovery();
522        if let Err(error) = self
523            .send_compact_request(Message::GetData(vec![hash.into()]), deadline)
524            .await
525        {
526            self.fail_with(error).await;
527            return;
528        }
529        if let State::AwaitingResponse { handler, .. } = &mut self.state {
530            *handler = Handler::BlocksByHash {
531                pending_hashes: HashSet::from([hash]),
532                blocks: Vec::with_capacity(1),
533            };
534            self.request_timer = Some(Box::pin(sleep_until(deadline)));
535        }
536    }
537
538    pub(super) async fn serve_compact_transactions(&mut self, request: BlockTransactionsRequest) {
539        if !self.connection_info.early_block_relay {
540            return;
541        }
542        self.compact.expire();
543        let Some((serving, Some(_), _)) = &self.compact.sent else {
544            return;
545        };
546        if serving.block.hash() != request.block_hash {
547            return;
548        }
549        // A request for no transactions gets no reply.
550        if request.indexes.is_empty()
551            || request
552                .indexes
553                .last()
554                .is_some_and(|index| *index >= serving.block.transactions.len())
555            || request.indexes.windows(2).any(|pair| pair[0] >= pair[1])
556        {
557            return;
558        }
559        // A request that doesn't fit the byte budget still uses its reply.
560        let Some(replies_left) = self.compact.recovery_replies_left.checked_sub(1) else {
561            return;
562        };
563        self.compact.recovery_replies_left = replies_left;
564        let overhead = request.block_hash.zcash_serialized_size()
565            + CompactSizeMessage::try_from(request.indexes.len())
566                .expect("recovery indexes are bounded by the advertised block")
567                .zcash_serialized_size();
568        let Some(remaining) = self
569            .compact
570            .recovery_bytes_left
571            .checked_sub(overhead)
572            .and_then(|remaining| {
573                request
574                    .indexes
575                    .iter()
576                    .try_fold(remaining, |remaining, index| {
577                        remaining
578                            .checked_sub(serving.block.transactions[*index].zcash_serialized_size())
579                    })
580            })
581        else {
582            return;
583        };
584        self.compact.recovery_bytes_left = remaining;
585        let transactions = request
586            .indexes
587            .into_iter()
588            .map(|index| serving.block.transactions[index].clone())
589            .collect();
590        let response = BlockTransactions {
591            block_hash: request.block_hash,
592            transactions,
593        };
594        // Repeated recovery shares the reply limit and a byte budget, and requests are only answered
595        // until the snapshot expires. The reply gets the usual send timeout, because an honest peer
596        // can ask late.
597        if let Err(error) = self
598            .peer_tx
599            .send(Message::BlockTransactions(response))
600            .await
601        {
602            self.compact.clear_sent();
603            self.fail_with(error).await;
604        }
605    }
606}
607
608/// Returns `compact` if its encoding is smaller than `block`'s encoding.
609///
610/// An announcement that wouldn't save bytes, or whose encoding fails, isn't sent, so the block is
611/// relayed with an ordinary block inventory instead.
612pub(super) fn smaller_announcement(compact: CompactBlock, block: &Block) -> Option<CompactBlock> {
613    (encoded_size(&compact)? < encoded_size(block)?).then_some(compact)
614}
615
616/// Returns the number of bytes in `value`'s encoding, or `None` if its encoding fails.
617fn encoded_size(value: &impl ZcashSerialize) -> Option<usize> {
618    let mut writer = FakeWriter(0);
619    value.zcash_serialize(&mut writer).ok()?;
620    Some(writer.0)
621}
622
623/// Returns the timer for the response to `handler`.
624///
625/// A block download that started through compact relay keeps the deadline it started with, so the
626/// whole download, including a fallback to the full block, has one request timeout.
627pub(super) fn response_timer(handler: &Handler, download_deadline: Option<Instant>) -> Sleep {
628    match (handler, download_deadline) {
629        (Handler::CompactBlock { deadline, .. }, _) => {
630            sleep_until((Instant::now() + RECOVERY_TIMEOUT).min(*deadline))
631        }
632        (_, Some(deadline)) => sleep_until(deadline),
633        (_, None) => sleep(constants::REQUEST_TIMEOUT),
634    }
635}