Skip to main content

zebra_network/peer_set/
inventory_registry.rs

1//! Inventory Registry Implementation
2//!
3//! [RFC]: https://zebra.zfnd.org/dev/rfcs/0003-inventory-tracking.html
4
5use std::{
6    pin::Pin,
7    task::{Context, Poll},
8};
9
10use futures::{FutureExt, Stream, StreamExt};
11use indexmap::{IndexMap, IndexSet};
12use tokio::{
13    sync::broadcast,
14    time::{self, Instant},
15};
16use tokio_stream::wrappers::{errors::BroadcastStreamRecvError, BroadcastStream, IntervalStream};
17
18use zebra_chain::serialization::AtLeastOne;
19
20use crate::{
21    constants::INVENTORY_ROTATION_INTERVAL,
22    protocol::{external::InventoryHash, internal::InventoryResponse},
23    BoxError, PeerSocketAddr,
24};
25
26use self::update::Update;
27
28/// Underlying type for the alias InventoryStatus::*
29use InventoryResponse::*;
30
31pub mod update;
32
33#[cfg(test)]
34mod tests;
35
36/// The maximum number of inventory hashes we will track from a single peer.
37///
38/// # Security
39///
40/// This limits known memory denial of service attacks like <https://invdos.net/> to a total of:
41/// ```text
42/// 1000 inventory * 2 maps * 32-64 bytes per inventory = less than 1 MB
43/// 1000 inventory * 70 peers * 2 maps * 6-18 bytes per address = up to 3 MB
44/// ```
45///
46/// Since the inventory registry is an efficiency optimisation, which falls back to a
47/// random peer, we only need to track a small number of hashes for available inventory.
48///
49/// But we want to be able to track a significant amount of missing inventory,
50/// to limit queries for globally missing inventory.
51//
52// TODO: split this into available (25) and missing (1000 or more?)
53pub const MAX_INV_PER_MAP: usize = 1000;
54
55/// The maximum number of peers we will track inventory for.
56///
57/// # Security
58///
59/// This limits known memory denial of service attacks. See [`MAX_INV_PER_MAP`] for details.
60///
61/// Since the inventory registry is an efficiency optimisation, which falls back to a
62/// random peer, we only need to track a small number of peers per inv for available inventory.
63///
64/// But we want to be able to track missing inventory for almost all our peers,
65/// so we only query a few peers for inventory that is genuinely missing from the network.
66//
67// TODO: split this into available (25) and missing (70)
68pub const MAX_PEERS_PER_INV: usize = 70;
69
70/// A peer inventory status, which tracks a hash for both available and missing inventory.
71pub type InventoryStatus<T> = InventoryResponse<T, T>;
72
73/// A peer inventory status change, used in the inventory status channel.
74///
75/// For performance reasons, advertisements should only be tracked
76/// for hashes that are rare on the network.
77/// So Zebra only tracks single-block inventory messages.
78///
79/// For security reasons, all `notfound` rejections should be tracked.
80/// This also helps with performance, if the hash is rare on the network.
81pub type InventoryChange = InventoryStatus<(AtLeastOne<InventoryHash>, PeerSocketAddr)>;
82
83/// An internal marker used in inventory status hash maps.
84type InventoryMarker = InventoryStatus<()>;
85
86/// The number of repeat requests for a block that were sent to each group of peers, see
87/// [`InventoryRegistry::repeat_requests()`].
88#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
89pub struct RepeatRequests {
90    /// Requests sent to peers that advertised the block.
91    pub advertisers: usize,
92
93    /// Requests sent to peers that didn't advertise the block.
94    pub other_peers: usize,
95}
96
97/// An Inventory Registry for tracking recent inventory advertisements and missing inventory.
98///
99/// For more details please refer to the [RFC].
100///
101/// [RFC]: https://zebra.zfnd.org/dev/rfcs/0003-inventory-tracking.html
102pub struct InventoryRegistry {
103    /// Map tracking the latest inventory status from the current interval
104    /// period.
105    //
106    // TODO: split maps into available and missing, so we can limit them separately.
107    current: IndexMap<InventoryHash, IndexMap<PeerSocketAddr, InventoryMarker>>,
108
109    /// Map tracking inventory statuses from the previous interval period.
110    prev: IndexMap<InventoryHash, IndexMap<PeerSocketAddr, InventoryMarker>>,
111
112    /// Map tracking peers that failed to return inventory in the current interval period.
113    ///
114    /// A failure is a completed peer error or response timeout, not caller cancellation or a
115    /// `notfound` response. Missing inventory is tracked separately; failed peers might still have it.
116    ///
117    /// Failures are tracked separately from inventory statuses, so a peer can't clear its failure
118    /// by advertising the inventory again.
119    ///
120    /// # Security
121    ///
122    /// This map is limited like the status maps, using [`MAX_INV_PER_MAP`] and
123    /// [`MAX_PEERS_PER_INV`]. So it uses up to 3 MB for both intervals.
124    failed_current: IndexMap<InventoryHash, IndexSet<PeerSocketAddr>>,
125
126    /// Map tracking peers that failed to return inventory in the previous interval period.
127    failed_prev: IndexMap<InventoryHash, IndexSet<PeerSocketAddr>>,
128
129    /// Map tracking the peers that answered a request for inventory with a `notfound` that
130    /// lists it, in the current interval period. Routing treats these peers as missing it.
131    ///
132    /// # Security
133    ///
134    /// The inventory collector only keeps the first [`MAX_INV_PER_MAP`] hashes of a `notfound`,
135    /// and any peer can evict the oldest inventory statuses by sending that many new hashes, then
136    /// advertise the inventory again. So refusals are tracked separately, and only the peer set
137    /// records them. Otherwise, a peer that advertises a block and refuses it could get every
138    /// retry for it (GHSA-65g4-c4v4-9rfq).
139    ///
140    /// This map is limited like `failed_current`.
141    refused_current: IndexMap<InventoryHash, IndexSet<PeerSocketAddr>>,
142
143    /// Map tracking the peers that refused inventory in the previous interval period.
144    refused_prev: IndexMap<InventoryHash, IndexSet<PeerSocketAddr>>,
145
146    /// The blocks that some peer failed to return or refused in the current interval period, see
147    /// [`InventoryRegistry::is_repeat_request()`].
148    ///
149    /// # Security
150    ///
151    /// These records are kept per block, not per peer, so a peer can't remove them by
152    /// disconnecting or reconnecting. This set is limited using [`MAX_INV_PER_MAP`].
153    unanswered_current: IndexSet<InventoryHash>,
154
155    /// The blocks that some peer failed to return or refused in the previous interval period.
156    unanswered_prev: IndexSet<InventoryHash>,
157
158    /// Map tracking the peers that returned a block they were asked for because the block was
159    /// advertised, in the current interval period.
160    ///
161    /// # Security
162    ///
163    /// A caller only asks for a block again if it rejected the block it was given. So a second
164    /// request for one of these blocks shows that a peer that advertised it served something
165    /// else, and the advertisements for it can't be trusted. See
166    /// [`InventoryRegistry::served_peers()`].
167    ///
168    /// This map is limited like `failed_current`.
169    served_current: IndexMap<InventoryHash, IndexSet<PeerSocketAddr>>,
170
171    /// Map tracking the peers that returned an advertised block in the previous interval period.
172    served_prev: IndexMap<InventoryHash, IndexSet<PeerSocketAddr>>,
173
174    /// Map tracking the repeat requests sent for a block in the current interval period, see
175    /// [`InventoryRegistry::repeat_requests()`].
176    ///
177    /// This map is limited like `failed_current`.
178    repeat_current: IndexMap<InventoryHash, RepeatRequests>,
179
180    /// Map tracking the repeat requests sent for a block in the previous interval period.
181    repeat_prev: IndexMap<InventoryHash, RepeatRequests>,
182
183    /// Stream of incoming inventory statuses to register.
184    inv_stream: Pin<
185        Box<dyn Stream<Item = Result<InventoryChange, BroadcastStreamRecvError>> + Send + 'static>,
186    >,
187
188    /// Interval tracking when we should next rotate our maps.
189    interval: IntervalStream,
190}
191
192impl std::fmt::Debug for InventoryRegistry {
193    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
194        f.debug_struct("InventoryRegistry")
195            .field("current", &self.current)
196            .field("prev", &self.prev)
197            .finish()
198    }
199}
200
201impl InventoryChange {
202    /// Returns a new available inventory change from a single hash.
203    pub fn new_available(hash: InventoryHash, peer: PeerSocketAddr) -> Self {
204        let bv = AtLeastOne::from_vec(vec![hash]).expect("bounded vec must fit");
205        InventoryStatus::Available((bv, peer))
206    }
207
208    /// Returns a new missing inventory change from a single hash.
209    #[allow(dead_code)]
210    pub fn new_missing(hash: InventoryHash, peer: PeerSocketAddr) -> Self {
211        let bv = AtLeastOne::from_vec(vec![hash]).expect("bounded vec must fit");
212        InventoryStatus::Missing((bv, peer))
213    }
214
215    /// Returns a new available multiple inventory change, if `hashes` contains at least one change.
216    pub fn new_available_multi<'a>(
217        hashes: impl IntoIterator<Item = &'a InventoryHash>,
218        peer: PeerSocketAddr,
219    ) -> Option<Self> {
220        let mut hashes: Vec<InventoryHash> = hashes.into_iter().copied().collect();
221
222        // # Security
223        //
224        // Don't send more hashes than we're going to store.
225        // It doesn't matter which hashes we choose, because this is an efficiency optimisation.
226        //
227        //  This limits known memory denial of service attacks to:
228        // `1000 hashes * 200 peers/channel capacity * 32-64 bytes = up to 12 MB`
229        hashes.truncate(MAX_INV_PER_MAP);
230
231        let hashes = hashes.try_into().ok();
232
233        hashes.map(|hashes| InventoryStatus::Available((hashes, peer)))
234    }
235
236    /// Returns a new missing multiple inventory change, if `hashes` contains at least one change.
237    pub fn new_missing_multi<'a>(
238        hashes: impl IntoIterator<Item = &'a InventoryHash>,
239        peer: PeerSocketAddr,
240    ) -> Option<Self> {
241        let mut hashes: Vec<InventoryHash> = hashes.into_iter().copied().collect();
242
243        // # Security
244        //
245        // Don't send more hashes than we're going to store. The peer set records refusals of the
246        // blocks it requests itself, so it doesn't matter which hashes we choose: this is an
247        // efficiency optimisation.
248        hashes.truncate(MAX_INV_PER_MAP);
249
250        let hashes = hashes.try_into().ok();
251
252        hashes.map(|hashes| InventoryStatus::Missing((hashes, peer)))
253    }
254}
255
256impl<T> InventoryStatus<T> {
257    /// Get a marker for the status, without any associated data.
258    pub fn marker(&self) -> InventoryMarker {
259        self.as_ref().map(|_inner| ())
260    }
261
262    /// Maps an `InventoryStatus<T>` to `InventoryStatus<U>` by applying a function to a contained value.
263    pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> InventoryStatus<U> {
264        // Based on Option::map from https://doc.rust-lang.org/src/core/option.rs.html#844
265        match self {
266            Available(item) => Available(f(item)),
267            Missing(item) => Missing(f(item)),
268        }
269    }
270}
271
272impl<T: Clone> InventoryStatus<T> {
273    /// Returns a clone of the inner item, regardless of status.
274    pub fn to_inner(&self) -> T {
275        match self {
276            Available(item) | Missing(item) => item.clone(),
277        }
278    }
279}
280
281impl InventoryRegistry {
282    /// Returns a new Inventory Registry for `inv_stream`.
283    pub fn new(inv_stream: broadcast::Receiver<InventoryChange>) -> Self {
284        let interval = INVENTORY_ROTATION_INTERVAL;
285
286        // Don't do an immediate rotation, current and prev are already empty.
287        let mut interval = tokio::time::interval_at(Instant::now() + interval, interval);
288        // # Security
289        //
290        // Delay missed ticks so newly registered inventory survives a full interval.
291        // Per-map caps bound memory use even when polling is delayed.
292        interval.set_missed_tick_behavior(time::MissedTickBehavior::Delay);
293
294        Self {
295            current: Default::default(),
296            prev: Default::default(),
297            failed_current: Default::default(),
298            failed_prev: Default::default(),
299            refused_current: Default::default(),
300            refused_prev: Default::default(),
301            unanswered_current: Default::default(),
302            unanswered_prev: Default::default(),
303            served_current: Default::default(),
304            served_prev: Default::default(),
305            repeat_current: Default::default(),
306            repeat_prev: Default::default(),
307            inv_stream: BroadcastStream::new(inv_stream).boxed(),
308            interval: IntervalStream::new(interval),
309        }
310    }
311
312    /// Returns an iterator over addrs of peers that have recently advertised `hash` in their
313    /// inventory, and haven't refused it since.
314    pub fn advertising_peers(&self, hash: InventoryHash) -> impl Iterator<Item = &PeerSocketAddr> {
315        self.status_peers(hash)
316            .filter_map(|addr_status| addr_status.available())
317            .filter(move |addr| !self.has_refused(hash, addr))
318    }
319
320    /// Returns an iterator over addrs of peers that have recently missed `hash` in their
321    /// inventory, or refused it.
322    ///
323    /// Can include the same peer twice, if it refused `hash` in the current and previous interval.
324    pub fn missing_peers(&self, hash: InventoryHash) -> impl Iterator<Item = &PeerSocketAddr> {
325        let refused = self
326            .refused_current
327            .get(&hash)
328            .into_iter()
329            .chain(self.refused_prev.get(&hash))
330            .flatten();
331
332        self.status_peers(hash)
333            .filter_map(|addr_status| addr_status.missing())
334            .filter(move |addr| !self.has_refused(hash, addr))
335            .chain(refused)
336    }
337
338    /// Records that `peer` answered a request for `hash` with a `notfound` that lists it.
339    ///
340    /// These records expire after the registry rotates twice, like inventory statuses. Unlike
341    /// failures, they are about the peer's address, not its connection.
342    pub fn register_refused(&mut self, hash: InventoryHash, peer: PeerSocketAddr) {
343        Self::register_peer(&mut self.refused_current, hash, peer);
344    }
345
346    /// Returns true if `peer` recently refused `hash`.
347    fn has_refused(&self, hash: InventoryHash, peer: &PeerSocketAddr) -> bool {
348        [&self.refused_current, &self.refused_prev]
349            .into_iter()
350            .any(|map| map.get(&hash).is_some_and(|peers| peers.contains(peer)))
351    }
352
353    /// Returns an iterator over addrs of peers that recently failed to return `hash`.
354    ///
355    /// Can include the same peer twice, if it failed in the current and previous interval.
356    pub fn failed_peers(&self, hash: InventoryHash) -> impl Iterator<Item = &PeerSocketAddr> {
357        self.failed_current
358            .get(&hash)
359            .into_iter()
360            .chain(self.failed_prev.get(&hash))
361            .flatten()
362    }
363
364    /// Records that `peer` failed to return `hash`.
365    ///
366    /// Failures expire after the registry rotates twice, like inventory statuses.
367    pub fn register_failed(&mut self, hash: InventoryHash, peer: PeerSocketAddr) {
368        Self::register_peer(&mut self.failed_current, hash, peer);
369    }
370
371    /// Records that a peer failed to return `hash` or answered `notfound` for it, whether or not
372    /// that peer is still connected.
373    ///
374    /// These records expire after the registry rotates twice, like inventory statuses.
375    pub fn register_unanswered(&mut self, hash: InventoryHash) {
376        let (index, _) = self.unanswered_current.insert_full(hash);
377        self.unanswered_current
378            .move_index(index, self.unanswered_current.len() - 1);
379
380        // # Security
381        //
382        // Limit the number of stored hashes, removing the oldest entries, like `register_peer()`.
383        if self.unanswered_current.len() > MAX_INV_PER_MAP {
384            // Performance: `MAX_INV_PER_MAP` is small, so O(n) performance is acceptable.
385            self.unanswered_current.shift_remove_index(0);
386        }
387    }
388
389    /// Returns true if a request for `hash` is a repeat: a peer recently failed to return
390    /// `hash`, refused it, or returned it after it was chosen for an advertisement or in a repeat request.
391    ///
392    /// # Security
393    ///
394    /// The advertisements for a block can't be trusted once a request for it didn't deliver a
395    /// block the caller accepted. A peer can advertise a block and serve its header with other
396    /// transactions (GHSA-g9rc-89v4-hhvf), or advertise it from many addresses and never answer
397    /// or answer `notfound` (GHSA-g9wm-xjq3-x3c2). Advertising is free, so in both cases the peers that advertised
398    /// the block must not get every request for it. See [`InventoryRegistry::repeat_requests()`].
399    pub fn is_repeat_request(&self, hash: InventoryHash) -> bool {
400        self.unanswered_current.contains(&hash)
401            || self.unanswered_prev.contains(&hash)
402            || self.served_peers(hash).next().is_some()
403    }
404
405    /// Returns an iterator over addrs of peers that recently returned `hash` when they were asked
406    /// for it because it was advertised, or in a repeat request.
407    ///
408    /// Can include the same peer twice, if it returned `hash` in the current and previous interval.
409    ///
410    /// # Security
411    ///
412    /// If this isn't empty, a request for `hash` is a repeat: the caller rejected the block one
413    /// of these peers gave it. A block hash only commits to the header, so a peer can advertise a
414    /// block and then serve its header with other transactions. So the caller should only ask
415    /// these peers as a last resort.
416    ///
417    /// Several peers can advertise the same block to get each retry in turn, and the caller can't
418    /// tell them from the honest peers that advertised it. See
419    /// [`InventoryRegistry::repeat_answer_count()`].
420    pub fn served_peers(&self, hash: InventoryHash) -> impl Iterator<Item = &PeerSocketAddr> {
421        self.served_current
422            .get(&hash)
423            .into_iter()
424            .chain(self.served_prev.get(&hash))
425            .flatten()
426    }
427
428    /// Records that `peer` returned `hash` when it was asked for it because it was advertised, or
429    /// in a repeat request.
430    ///
431    /// These records expire after the registry rotates twice, like inventory statuses.
432    pub fn register_served(&mut self, hash: InventoryHash, peer: PeerSocketAddr) {
433        Self::register_peer(&mut self.served_current, hash, peer);
434    }
435
436    /// Returns how many repeat requests for `hash` were recently sent to the peers that
437    /// advertised it, and to the peers that didn't.
438    ///
439    /// # Security
440    ///
441    /// The peers that advertised `hash` and the peers that didn't take turns to get the repeat
442    /// requests for it, and these counts decide whose turn it is. A peer that forges blocks can
443    /// advertise them from several addresses, and it can also connect from addresses that don't
444    /// advertise them and don't answer. So if either group got every repeat request, that group
445    /// could keep them all from the honest peers.
446    ///
447    /// Requests are counted when they are sent, not when they are answered. So several repeat
448    /// requests in flight at the same time take turns too, and a peer can't change the turn by
449    /// delaying its answer.
450    pub fn repeat_requests(&self, hash: InventoryHash) -> RepeatRequests {
451        let current = self.repeat_current.get(&hash).copied().unwrap_or_default();
452        let prev = self.repeat_prev.get(&hash).copied().unwrap_or_default();
453
454        RepeatRequests {
455            advertisers: current.advertisers.saturating_add(prev.advertisers),
456            other_peers: current.other_peers.saturating_add(prev.other_peers),
457        }
458    }
459
460    /// Records that a repeat request for `hash` was sent to a peer that advertised it, if
461    /// `advertised` is true, or to a peer that didn't.
462    ///
463    /// These records expire after the registry rotates twice, like inventory statuses.
464    pub fn register_repeat_request(&mut self, hash: InventoryHash, advertised: bool) {
465        if let Some(index) = self.repeat_current.get_index_of(&hash) {
466            self.repeat_current
467                .move_index(index, self.repeat_current.len() - 1);
468        }
469        let requests = self.repeat_current.entry(hash).or_default();
470        if advertised {
471            requests.advertisers = requests.advertisers.saturating_add(1);
472        } else {
473            requests.other_peers = requests.other_peers.saturating_add(1);
474        }
475
476        // # Security
477        //
478        // Limit the number of stored hashes, removing the oldest entries, like `register_peer()`.
479        if self.repeat_current.len() > MAX_INV_PER_MAP {
480            // Performance: `MAX_INV_PER_MAP` is small, so O(n) performance is acceptable.
481            self.repeat_current.shift_remove_index(0);
482        }
483    }
484
485    /// Adds `peer` to the peers for `hash` in `map`, as the newest entry.
486    fn register_peer(
487        map: &mut IndexMap<InventoryHash, IndexSet<PeerSocketAddr>>,
488        hash: InventoryHash,
489        peer: PeerSocketAddr,
490    ) {
491        if let Some(index) = map.get_index_of(&hash) {
492            map.move_index(index, map.len() - 1);
493        }
494        let peers = map.entry(hash).or_default();
495        let (index, _) = peers.insert_full(peer);
496        peers.move_index(index, peers.len() - 1);
497
498        // # Security
499        //
500        // Limit the number of stored peers and hashes, removing the oldest entries, like
501        // `register()`.
502        if peers.len() > MAX_PEERS_PER_INV {
503            // Performance: `MAX_PEERS_PER_INV` is small, so O(n) performance is acceptable.
504            peers.shift_remove_index(0);
505        }
506        if map.len() > MAX_INV_PER_MAP {
507            // Performance: `MAX_INV_PER_MAP` is small, so O(n) performance is acceptable.
508            map.shift_remove_index(0);
509        }
510    }
511
512    /// Clears failures from previous connections that used `peer`'s transient address.
513    pub fn clear_peer_failures(&mut self, peer: PeerSocketAddr) {
514        for failures in [&mut self.failed_current, &mut self.failed_prev] {
515            failures.retain(|_, peers| {
516                peers.shift_remove(&peer);
517                !peers.is_empty()
518            });
519        }
520    }
521
522    /// Returns an iterator over peer inventory statuses for `hash`.
523    ///
524    /// Prefers current statuses to previously rotated statuses for the same peer.
525    pub fn status_peers(
526        &self,
527        hash: InventoryHash,
528    ) -> impl Iterator<Item = InventoryStatus<&PeerSocketAddr>> {
529        let prev = self.prev.get(&hash);
530        let current = self.current.get(&hash);
531
532        // # Security
533        //
534        // Prefer `current` statuses for the same peer over previously rotated statuses.
535        // This makes sure Zebra is using the most up-to-date network information.
536        let prev = prev
537            .into_iter()
538            .flatten()
539            .filter(move |(addr, _status)| !self.has_current_status(hash, **addr));
540        let current = current.into_iter().flatten();
541
542        current
543            .chain(prev)
544            .map(|(addr, status)| status.map(|()| addr))
545    }
546
547    /// Returns true if there is a current status entry for `hash` and `addr`.
548    pub fn has_current_status(&self, hash: InventoryHash, addr: PeerSocketAddr) -> bool {
549        self.current
550            .get(&hash)
551            .and_then(|current| current.get(&addr))
552            .is_some()
553    }
554
555    /// Returns an iterator over peer inventory status hashes.
556    ///
557    /// Yields current statuses first, then previously rotated statuses.
558    /// This can include multiple statuses for the same hash.
559    #[allow(dead_code)]
560    pub fn status_hashes(
561        &self,
562    ) -> impl Iterator<Item = (&InventoryHash, &IndexMap<PeerSocketAddr, InventoryMarker>)> {
563        self.current.iter().chain(self.prev.iter())
564    }
565
566    /// Returns a future that waits for new registry updates.
567    #[allow(dead_code)]
568    pub fn update(&mut self) -> Update<'_> {
569        Update::new(self)
570    }
571
572    /// Drive periodic inventory tasks.
573    ///
574    /// Rotates the inventory HashMaps on every timer tick.
575    /// Drains the inv_stream channel and registers all advertised inventory.
576    ///
577    /// Returns an error if the inventory channel is closed.
578    ///
579    /// Otherwise, returns `Ok` if it performed at least one update or rotation, or `Poll::Pending`
580    /// if there was no inventory change. Always registers a wakeup for the next inventory update
581    /// or rotation, even when it returns `Ok`.
582    pub fn poll_inventory(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), BoxError>> {
583        let mut result = Poll::Pending;
584
585        // # Correctness
586        //
587        // Registers the current task for wakeup when the timer next becomes ready.
588        // (But doesn't return, because we also want to register the task for wakeup when more
589        // inventory arrives.)
590        //
591        // # Security
592        //
593        // Rotate before registering new inventory. Missed ticks restart the interval, so
594        // repeated polls cannot immediately age out new advertisements or failures.
595        if Pin::new(&mut self.interval).poll_next(cx).is_ready() {
596            self.rotate();
597            result = Poll::Ready(Ok(()));
598        }
599
600        // This module uses a broadcast channel instead of an mpsc channel, even
601        // though there's a single consumer of inventory advertisements, because
602        // the broadcast channel has ring-buffer behavior: when the channel is
603        // full, sending a new message displaces the oldest message in the
604        // channel.
605        //
606        // This is the behavior we want for inventory advertisements, because we
607        // want to have a bounded buffer of unprocessed advertisements, and we
608        // want to prioritize new inventory (which is likely only at a specific
609        // peer) over old inventory (which is likely more widely distributed).
610        //
611        // The broadcast channel reports dropped messages by returning
612        // `RecvError::Lagged`. It's crucial that we handle that error here
613        // rather than propagating it through the peer set's Service::poll_ready
614        // implementation, where reporting a failure means reporting a permanent
615        // failure of the peer set.
616
617        // Returns Pending if all messages are processed, but the channel could get more.
618        loop {
619            let channel_result = self.inv_stream.next().poll_unpin(cx);
620
621            match channel_result {
622                Poll::Ready(Some(Ok(change))) => {
623                    self.register(change);
624                    result = Poll::Ready(Ok(()));
625                }
626                Poll::Ready(Some(Err(BroadcastStreamRecvError::Lagged(count)))) => {
627                    // This isn't a fatal inventory error, it's expected behaviour when Zebra is
628                    // under load from peers.
629                    metrics::counter!("pool.inventory.dropped").increment(1);
630                    metrics::counter!("pool.inventory.dropped.messages").increment(count);
631
632                    // If this message happens a lot, we should improve inventory registry
633                    // performance, or poll the registry or peer set in a separate task.
634                    info!(count, "dropped lagged inventory advertisements");
635                }
636                Poll::Ready(None) => {
637                    // If the channel is empty and returns None, all senders, including the one in
638                    // the handshaker, have been dropped, which really is a permanent failure.
639                    result = Poll::Ready(Err(broadcast::error::RecvError::Closed.into()));
640                }
641                Poll::Pending => {
642                    break;
643                }
644            }
645        }
646
647        result
648    }
649
650    /// Record the given inventory `change` for the peer `addr`.
651    ///
652    /// `Missing` markers are not updated until the registry rotates, for security reasons.
653    fn register(&mut self, change: InventoryChange) {
654        let new_status = change.marker();
655        let (invs, addr) = change.to_inner();
656
657        for inv in invs {
658            use InventoryHash::*;
659            assert!(
660                matches!(inv, Block(_) | Tx(_) | Wtx(_)),
661                "unexpected inventory type: {inv:?} from peer: {addr:?}",
662            );
663
664            let hash_peers = self.current.entry(inv).or_default();
665
666            // # Security
667            //
668            // Prefer `missing` over `advertised`, so malicious peers can't reset their own entries,
669            // and funnel multiple failing requests to themselves.
670            if let Some(old_status) = hash_peers.get(&addr) {
671                if old_status.is_missing() && new_status.is_available() {
672                    debug!(?new_status, ?old_status, ?addr, ?inv, "skipping new status");
673                    continue;
674                }
675
676                debug!(
677                    ?new_status,
678                    ?old_status,
679                    ?addr,
680                    ?inv,
681                    "keeping both new and old status"
682                );
683            }
684
685            let replaced_status = hash_peers.insert(addr, new_status);
686
687            debug!(
688                ?new_status,
689                ?replaced_status,
690                ?addr,
691                ?inv,
692                "inserted new status"
693            );
694
695            // # Security
696            //
697            // Limit the number of stored peers per hash, removing the oldest entries,
698            // because newer entries are likely to be more relevant.
699            //
700            // TODO: do random or weighted random eviction instead?
701            if hash_peers.len() > MAX_PEERS_PER_INV {
702                // Performance: `MAX_PEERS_PER_INV` is small, so O(n) performance is acceptable.
703                hash_peers.shift_remove_index(0);
704            }
705
706            // # Security
707            //
708            // Limit the number of stored inventory hashes, removing the oldest entries,
709            // because newer entries are likely to be more relevant.
710            //
711            // TODO: do random or weighted random eviction instead?
712            if self.current.len() > MAX_INV_PER_MAP {
713                // Performance: `MAX_INV_PER_MAP` is small, so O(n) performance is acceptable.
714                self.current.shift_remove_index(0);
715            }
716        }
717    }
718
719    /// Replace the prev HashMap with current's and replace current with an empty
720    /// HashMap
721    fn rotate(&mut self) {
722        self.prev = std::mem::take(&mut self.current);
723        self.failed_prev = std::mem::take(&mut self.failed_current);
724        self.refused_prev = std::mem::take(&mut self.refused_current);
725        self.unanswered_prev = std::mem::take(&mut self.unanswered_current);
726        self.served_prev = std::mem::take(&mut self.served_current);
727        self.repeat_prev = std::mem::take(&mut self.repeat_current);
728    }
729}