Skip to main content

zebra_network/peer_set/set/
tests.rs

1//! Peer set unit tests, and test setup code.
2
3#![allow(clippy::unwrap_in_result)]
4
5#[cfg(test)]
6use std::net::SocketAddr;
7use std::{net::IpAddr, sync::Arc};
8
9use futures::channel::mpsc;
10#[cfg(test)]
11use futures::{stream, Stream, StreamExt};
12#[cfg(test)]
13use proptest::{collection::vec, prelude::*};
14#[cfg(test)]
15use proptest_derive::Arbitrary;
16use tokio::{
17    sync::{broadcast, watch},
18    task::JoinHandle,
19};
20#[cfg(test)]
21use tower::discover::Change;
22use tower::{discover::Discover, BoxError};
23use tracing::Span;
24
25#[cfg(test)]
26use zebra_chain::{block, parameters::NetworkUpgrade};
27use zebra_chain::{chain_tip::ChainTip, parameters::Network};
28
29use crate::{
30    address_book::AddressMetrics,
31    constants::DEFAULT_MAX_CONNS_PER_IP,
32    peer::{LoadTrackedClient, MinimumPeerVersion},
33    peer_set::{set::MorePeers, InventoryChange, PeerSet},
34    AddressBook, Config, PeerSocketAddr,
35};
36#[cfg(test)]
37use crate::{peer::ClientTestHarness, protocol::external::types::Version};
38
39pub mod consumer;
40
41#[cfg(test)]
42mod bans;
43
44#[cfg(test)]
45mod prop;
46
47#[cfg(test)]
48mod vectors;
49
50/// The maximum number of arbitrary peers to generate in [`PeerVersions`].
51///
52/// This affects the maximum number of peer connections added to the [`PeerSet`] during the tests.
53#[cfg(test)]
54const MAX_PEERS: usize = 20;
55
56/// A helper type to generate arbitrary peer versions which can then become mock peer services.
57#[cfg(test)]
58#[derive(Arbitrary, Debug)]
59struct PeerVersions {
60    #[proptest(strategy = "vec(any::<Version>(), 1..MAX_PEERS)")]
61    peer_versions: Vec<Version>,
62}
63
64#[cfg(test)]
65impl PeerVersions {
66    /// Convert the arbitrary peer versions into mock peer services.
67    ///
68    /// Each peer versions results in a mock peer service, which is returned as a tuple. The first
69    /// element is the [`LeadTrackedClient`], which is the actual service for the peer connection.
70    /// The second element is a [`ClientTestHarness`], which contains the open endpoints of the
71    /// mock channels used by the peer service.
72    ///
73    /// The clients and the harnesses are collected into separate [`Vec`] lists and returned.
74    pub fn mock_peers(&self) -> (Vec<LoadTrackedClient>, Vec<ClientTestHarness>) {
75        let mut clients = Vec::with_capacity(self.peer_versions.len());
76        let mut harnesses = Vec::with_capacity(self.peer_versions.len());
77
78        for peer_version in &self.peer_versions {
79            let (client, harness) = ClientTestHarness::build()
80                .with_version(*peer_version)
81                .finish();
82
83            clients.push(client.into());
84            harnesses.push(harness);
85        }
86
87        (clients, harnesses)
88    }
89
90    /// Convert the arbitrary peer versions into mock peer services available through a
91    /// [`Discover`] compatible stream.
92    ///
93    /// A tuple is returned, where the first item is a stream with the mock peers available through
94    /// a [`Discover`] interface, and the second is a list of harnesses to the mocked services.
95    ///
96    /// The returned stream never finishes, so it is ready to be passed to the [`PeerSet`]
97    /// constructor.
98    ///
99    /// See [`Self::mock_peers`] for details on how the peers are mocked and on what the harnesses
100    /// contain.
101    pub fn mock_peer_discovery(
102        &self,
103    ) -> (
104        impl Stream<Item = Result<Change<PeerSocketAddr, LoadTrackedClient>, BoxError>>,
105        Vec<ClientTestHarness>,
106    ) {
107        let (clients, harnesses) = self.mock_peers();
108        let fake_ports = 1_u16..;
109
110        let discovered_peers_iterator = fake_ports.zip(clients).map(|(port, client)| {
111            let peer_address: PeerSocketAddr = SocketAddr::new([127, 0, 0, 1].into(), port).into();
112
113            Ok(Change::Insert(peer_address, client))
114        });
115
116        let discovered_peers = stream::iter(discovered_peers_iterator).chain(stream::pending());
117
118        (discovered_peers, harnesses)
119    }
120}
121
122/// Discover one peer advertising `start_height`, and return its request harness.
123#[cfg(test)]
124fn mock_peer_discovery_with_start_height(
125    start_height: block::Height,
126) -> (
127    impl Stream<Item = Result<Change<PeerSocketAddr, LoadTrackedClient>, BoxError>>,
128    ClientTestHarness,
129) {
130    let (client, harness) = ClientTestHarness::build()
131        .with_version(crate::constants::CURRENT_NETWORK_PROTOCOL_VERSION)
132        .with_start_height(start_height)
133        .finish();
134    let peer_address: PeerSocketAddr = SocketAddr::new([127, 0, 0, 1].into(), 1).into();
135    let discovery =
136        stream::iter([Ok(Change::Insert(peer_address, client.into()))]).chain(stream::pending());
137
138    (discovery, harness)
139}
140
141/// A helper builder type for creating test [`PeerSet`] instances.
142///
143/// This helps to reduce repeated boilerplate code. Fields that are not set are configured to use
144/// dummy fallbacks.
145#[derive(Default)]
146pub(crate) struct PeerSetBuilder<D, C> {
147    config: Option<Config>,
148    discover: Option<D>,
149    demand_signal: Option<mpsc::Sender<MorePeers>>,
150    handle_rx: Option<tokio::sync::oneshot::Receiver<Vec<JoinHandle<Result<(), BoxError>>>>>,
151    inv_stream: Option<broadcast::Receiver<InventoryChange>>,
152    address_book: Option<Arc<std::sync::Mutex<AddressBook>>>,
153    minimum_peer_version: Option<MinimumPeerVersion<C>>,
154    max_conns_per_ip: Option<usize>,
155    block_gossip_peer_ips: Vec<IpAddr>,
156}
157
158impl PeerSetBuilder<(), ()> {
159    /// Create a new [`PeerSetBuilder`] instance.
160    pub fn new() -> Self {
161        PeerSetBuilder::default()
162    }
163}
164
165impl<D, C> PeerSetBuilder<D, C> {
166    /// Use the provided [`Config`] when constructing the [`PeerSet`] instance.
167    #[cfg(test)]
168    pub fn with_config(self, config: Config) -> PeerSetBuilder<D, C> {
169        PeerSetBuilder {
170            config: Some(config),
171            ..self
172        }
173    }
174
175    /// Always include these inbound peer IPs in block inventory broadcasts.
176    #[cfg(test)]
177    pub fn with_block_gossip_peer_ips(
178        self,
179        block_gossip_peer_ips: Vec<IpAddr>,
180    ) -> PeerSetBuilder<D, C> {
181        PeerSetBuilder {
182            block_gossip_peer_ips,
183            ..self
184        }
185    }
186
187    /// Use the provided `discover` parameter when constructing the [`PeerSet`] instance.
188    pub fn with_discover<NewD>(self, discover: NewD) -> PeerSetBuilder<NewD, C> {
189        PeerSetBuilder {
190            discover: Some(discover),
191            config: self.config,
192            demand_signal: self.demand_signal,
193            handle_rx: self.handle_rx,
194            inv_stream: self.inv_stream,
195            address_book: self.address_book,
196            minimum_peer_version: self.minimum_peer_version,
197            max_conns_per_ip: self.max_conns_per_ip,
198            block_gossip_peer_ips: self.block_gossip_peer_ips,
199        }
200    }
201
202    /// Use the provided [`MinimumPeerVersion`] instance when constructing the [`PeerSet`] instance.
203    pub fn with_minimum_peer_version<NewC>(
204        self,
205        minimum_peer_version: MinimumPeerVersion<NewC>,
206    ) -> PeerSetBuilder<D, NewC> {
207        PeerSetBuilder {
208            config: self.config,
209            discover: self.discover,
210            demand_signal: self.demand_signal,
211            handle_rx: self.handle_rx,
212            inv_stream: self.inv_stream,
213            address_book: self.address_book,
214            minimum_peer_version: Some(minimum_peer_version),
215            max_conns_per_ip: self.max_conns_per_ip,
216            block_gossip_peer_ips: self.block_gossip_peer_ips,
217        }
218    }
219
220    /// Use the provided [`MinimumPeerVersion`] instance when constructing the [`PeerSet`] instance.
221    #[cfg(test)]
222    pub fn max_conns_per_ip(self, max_conns_per_ip: usize) -> PeerSetBuilder<D, C> {
223        assert!(
224            max_conns_per_ip > 0,
225            "max_conns_per_ip must be greater than zero"
226        );
227
228        PeerSetBuilder {
229            config: self.config,
230            discover: self.discover,
231            demand_signal: self.demand_signal,
232            handle_rx: self.handle_rx,
233            inv_stream: self.inv_stream,
234            address_book: self.address_book,
235            minimum_peer_version: self.minimum_peer_version,
236            max_conns_per_ip: Some(max_conns_per_ip),
237            block_gossip_peer_ips: self.block_gossip_peer_ips,
238        }
239    }
240}
241
242impl<D, C> PeerSetBuilder<D, C>
243where
244    D: Discover<Key = PeerSocketAddr, Service = LoadTrackedClient> + Unpin,
245    D::Error: Into<BoxError>,
246    C: ChainTip,
247{
248    /// Finish building the [`PeerSet`] instance.
249    ///
250    /// Returns a tuple with the [`PeerSet`] instance and a [`PeerSetGuard`] to keep track of some
251    /// endpoints of channels created for the [`PeerSet`].
252    pub fn build(self) -> (PeerSet<D, C>, PeerSetGuard) {
253        let mut guard = PeerSetGuard::new();
254
255        let config = self.config.unwrap_or_default();
256        let discover = self.discover.expect("`discover` must be set");
257        let minimum_peer_version = self
258            .minimum_peer_version
259            .expect("`minimum_peer_version` must be set");
260        let max_conns_per_ip = self.max_conns_per_ip;
261
262        let demand_signal = self
263            .demand_signal
264            .unwrap_or_else(|| guard.create_demand_sender());
265        let handle_rx = self
266            .handle_rx
267            .unwrap_or_else(|| guard.create_background_tasks_receiver());
268        let inv_stream = self
269            .inv_stream
270            .unwrap_or_else(|| guard.create_inventory_receiver());
271
272        let address_metrics = guard.prepare_address_book(self.address_book);
273        let (_bans_sender, bans_receiver) = tokio::sync::watch::channel(Default::default());
274
275        let peer_set = PeerSet::new(
276            &config,
277            self.block_gossip_peer_ips,
278            discover,
279            demand_signal,
280            handle_rx,
281            inv_stream,
282            bans_receiver,
283            address_metrics,
284            minimum_peer_version,
285            max_conns_per_ip,
286        );
287
288        (peer_set, guard)
289    }
290}
291
292/// A helper type to keep track of some dummy endpoints sent to a test [`PeerSet`] instance.
293#[derive(Default)]
294pub struct PeerSetGuard {
295    background_tasks_sender:
296        Option<tokio::sync::oneshot::Sender<Vec<JoinHandle<Result<(), BoxError>>>>>,
297    demand_receiver: Option<mpsc::Receiver<MorePeers>>,
298    inventory_sender: Option<broadcast::Sender<InventoryChange>>,
299    address_book: Option<Arc<std::sync::Mutex<AddressBook>>>,
300}
301
302impl PeerSetGuard {
303    /// Create a new empty [`PeerSetGuard`] instance.
304    pub fn new() -> Self {
305        PeerSetGuard::default()
306    }
307
308    /// Return a mutable reference to the background tasks sender, if present.
309    #[allow(dead_code)]
310    pub fn background_tasks_sender(
311        &mut self,
312    ) -> &mut Option<tokio::sync::oneshot::Sender<Vec<JoinHandle<Result<(), BoxError>>>>> {
313        &mut self.background_tasks_sender
314    }
315
316    /// Return a mutable reference to the background tasks sender, if present.
317    #[allow(dead_code)]
318    pub fn demand_receiver(&mut self) -> &mut Option<mpsc::Receiver<MorePeers>> {
319        &mut self.demand_receiver
320    }
321
322    /// Return a mutable reference to the background tasks sender, if present.
323    pub fn inventory_sender(&mut self) -> &mut Option<broadcast::Sender<InventoryChange>> {
324        &mut self.inventory_sender
325    }
326
327    /// Return a mutable reference to the background tasks sender, if present.
328    #[allow(dead_code)]
329    pub fn address_book(&mut self) -> &mut Option<Arc<std::sync::Mutex<AddressBook>>> {
330        &mut self.address_book
331    }
332
333    /// Create a dummy channel for the background tasks sent to the [`PeerSet`].
334    ///
335    /// The sender is stored inside the [`PeerSetGuard`], while the receiver is returned to be
336    /// passed to the [`PeerSet`] constructor.
337    pub fn create_background_tasks_receiver(
338        &mut self,
339    ) -> tokio::sync::oneshot::Receiver<Vec<JoinHandle<Result<(), BoxError>>>> {
340        let (sender, receiver) = tokio::sync::oneshot::channel();
341
342        self.background_tasks_sender = Some(sender);
343
344        receiver
345    }
346
347    /// Create a dummy channel for the [`PeerSet`] to send demand signals for more peers.
348    ///
349    /// The receiver is stored inside the [`PeerSetGuard`], while the sender is returned to be
350    /// passed to the [`PeerSet`] constructor.
351    pub fn create_demand_sender(&mut self) -> mpsc::Sender<MorePeers> {
352        let (sender, receiver) = mpsc::channel(1);
353
354        self.demand_receiver = Some(receiver);
355
356        sender
357    }
358
359    /// Create a dummy channel for the inventory hashes sent to the [`PeerSet`].
360    ///
361    /// The sender is stored inside the [`PeerSetGuard`], while the receiver is returned to be
362    /// passed to the [`PeerSet`] constructor.
363    pub fn create_inventory_receiver(&mut self) -> broadcast::Receiver<InventoryChange> {
364        let (sender, receiver) = broadcast::channel(1);
365
366        self.inventory_sender = Some(sender);
367
368        receiver
369    }
370
371    /// Prepare an [`AddressBook`] instance to send to the [`PeerSet`].
372    ///
373    /// If the `maybe_address_book` parameter contains an [`AddressBook`] instance, it is stored
374    /// inside the [`PeerSetGuard`] to keep track of it. Otherwise, a new instance is created with
375    /// the [`Self::fallback_address_book`] method.
376    ///
377    /// Returns a metrics watch channel for the [`AddressBook`] instance tracked by the [`PeerSetGuard`],
378    /// so it can be passed to the [`PeerSet`] constructor.
379    pub fn prepare_address_book(
380        &mut self,
381        maybe_address_book: Option<Arc<std::sync::Mutex<AddressBook>>>,
382    ) -> watch::Receiver<AddressMetrics> {
383        let address_book = maybe_address_book.unwrap_or_else(Self::fallback_address_book);
384        let metrics_watcher = address_book
385            .lock()
386            .expect("unexpected panic in previous address book mutex guard")
387            .address_metrics_watcher();
388
389        self.address_book = Some(address_book);
390
391        metrics_watcher
392    }
393
394    /// Create an empty [`AddressBook`] instance using a dummy local listener address.
395    fn fallback_address_book() -> Arc<std::sync::Mutex<AddressBook>> {
396        let local_listener = "127.0.0.1:1000"
397            .parse()
398            .expect("Invalid local listener address");
399        let address_book = AddressBook::new(
400            local_listener,
401            &Network::Mainnet,
402            DEFAULT_MAX_CONNS_PER_IP,
403            Span::none(),
404        );
405
406        Arc::new(std::sync::Mutex::new(address_book))
407    }
408}
409
410/// A pair of block height values, where one is before and the other is at or after an arbitrary
411/// network upgrade's activation height.
412#[cfg(test)]
413#[derive(Clone, Debug)]
414pub struct BlockHeightPairAcrossNetworkUpgrades {
415    /// The network for which the block height values represent heights before and after an
416    /// upgrade.
417    pub network: Network,
418
419    /// The block height before the network upgrade activation.
420    pub before_upgrade: block::Height,
421
422    /// The block height at or after the network upgrade activation.
423    pub after_upgrade: block::Height,
424}
425
426#[cfg(test)]
427impl Arbitrary for BlockHeightPairAcrossNetworkUpgrades {
428    type Parameters = ();
429
430    fn arbitrary_with((): Self::Parameters) -> Self::Strategy {
431        any::<(Network, NetworkUpgrade)>()
432            // Filter out genesis upgrade because there is no block height before genesis.
433            .prop_filter("no block height before genesis", |(_, upgrade)| {
434                !matches!(upgrade, NetworkUpgrade::Genesis)
435            })
436            // Filter out network upgrades without activation heights.
437            .prop_filter_map(
438                "missing activation height for network upgrade",
439                |(network, upgrade)| {
440                    upgrade
441                        .activation_height(&network)
442                        .map(|height| (network, height))
443                },
444            )
445            // Obtain random heights before and after (or at) the network upgrade activation.
446            .prop_flat_map(|(network, activation_height)| {
447                let before_upgrade_strategy = 0..activation_height.0;
448                let after_upgrade_strategy = activation_height.0..;
449
450                (
451                    Just(network),
452                    before_upgrade_strategy,
453                    after_upgrade_strategy,
454                )
455            })
456            // Collect the arbitrary values to build the final type.
457            .prop_map(|(network, before_upgrade_height, after_upgrade_height)| {
458                BlockHeightPairAcrossNetworkUpgrades {
459                    network,
460                    before_upgrade: block::Height(before_upgrade_height),
461                    after_upgrade: block::Height(after_upgrade_height),
462                }
463            })
464            .boxed()
465    }
466
467    type Strategy = BoxedStrategy<Self>;
468}