Skip to main content

zebra_network/peer/client/
tests.rs

1//! Tests for the [`Client`] part of peer connections, and some test utilities for mocking
2//! [`Client`] instances.
3
4#![allow(clippy::unwrap_in_result)]
5#![cfg_attr(feature = "proptest-impl", allow(dead_code))]
6
7use std::{
8    net::{Ipv4Addr, SocketAddrV4},
9    sync::Arc,
10};
11
12use chrono::Utc;
13use futures::{
14    channel::{mpsc, oneshot},
15    future::{self, AbortHandle, Future, FutureExt},
16};
17use tokio::task::JoinHandle;
18
19use zebra_chain::block::Height;
20
21use crate::{
22    constants,
23    peer::{
24        error::SharedPeerError, CancelHeartbeatTask, Client, ClientRequest, ConnectedAddr,
25        ConnectionInfo, ErrorSlot,
26    },
27    protocol::{
28        external::{types::Version, AddrInVersion},
29        types::{Nonce, PeerServices},
30    },
31    BoxError, VersionMessage,
32};
33
34#[cfg(test)]
35mod vectors;
36
37/// A harness with mocked channels for testing a [`Client`] instance.
38pub struct ClientTestHarness {
39    client_request_receiver: Option<mpsc::Receiver<ClientRequest>>,
40    /// Receives response-free block adverts from the mocked connection.
41    pub(crate) block_advert_receiver: tokio::sync::mpsc::Receiver<crate::peer_set::BlockAdvert>,
42    shutdown_receiver: Option<oneshot::Receiver<CancelHeartbeatTask>>,
43    error_slot: ErrorSlot,
44    remote_version: Version,
45    connection_aborter: AbortHandle,
46    heartbeat_aborter: AbortHandle,
47}
48
49/// A client request using the same response handling as a connection.
50pub struct ReceivedClientRequest(super::InProgressClientRequest);
51
52impl ReceivedClientRequest {
53    /// Returns the request sent through the real client channel.
54    pub fn request(&self) -> &crate::Request {
55        &self.0.request
56    }
57
58    /// Sends a response through the production response sender.
59    pub fn respond(self, response: Result<crate::Response, SharedPeerError>) {
60        let _ = self.0.tx.send(response);
61    }
62
63    /// Returns whether the caller dropped its response future.
64    pub fn is_canceled(&self) -> bool {
65        self.0.tx.is_canceled()
66    }
67}
68
69impl ClientTestHarness {
70    /// Create a [`ClientTestHarnessBuilder`] instance to help create a new [`Client`] instance
71    /// and a [`ClientTestHarness`] to track it.
72    pub fn build() -> ClientTestHarnessBuilder {
73        ClientTestHarnessBuilder {
74            version: None,
75            services: None,
76            start_height: None,
77            connection_task: None,
78            heartbeat_task: None,
79            connected_addr: None,
80        }
81    }
82
83    /// Gets the remote peer protocol version reported by the [`Client`].
84    pub fn remote_version(&self) -> Version {
85        self.remote_version
86    }
87
88    /// Acknowledge a mock connection's queued advert; real-write tests use `Connection::run`.
89    pub(crate) fn receive_block_advert(&mut self) -> zebra_chain::block::Hash {
90        let advert = self
91            .block_advert_receiver
92            .try_recv()
93            .expect("an advert was queued");
94        advert
95            .result
96            .send(Ok(()))
97            .expect("the advertiser is awaiting delivery");
98        advert.hash
99    }
100
101    /// Returns true if the [`Client`] instance still wants connection heartbeats to be sent.
102    ///
103    /// Checks that the client:
104    /// - has not been dropped,
105    /// - has not closed or dropped the mocked heartbeat task channel, and
106    /// - has not asked the mocked heartbeat task to shut down.
107    pub fn wants_connection_heartbeats(&mut self) -> bool {
108        let receive_result = self
109            .shutdown_receiver
110            .as_mut()
111            .expect("heartbeat shutdown receiver endpoint has been dropped")
112            .try_recv();
113
114        match receive_result {
115            Ok(None) => true,
116            Ok(Some(CancelHeartbeatTask)) | Err(oneshot::Canceled) => false,
117        }
118    }
119
120    /// Drops the mocked heartbeat shutdown receiver endpoint.
121    pub fn drop_heartbeat_shutdown_receiver(&mut self) {
122        let hearbeat_future = self
123            .shutdown_receiver
124            .take()
125            .expect("unexpected test failure: heartbeat shutdown receiver endpoint has already been dropped");
126
127        std::mem::drop(hearbeat_future);
128    }
129
130    /// Closes the receiver endpoint of [`ClientRequest`]s that are supposed to be sent to the
131    /// remote peer.
132    ///
133    /// The remote peer that would receive the requests is mocked for testing.
134    pub fn close_outbound_client_request_receiver(&mut self) {
135        self.client_request_receiver
136            .as_mut()
137            .expect("request receiver endpoint has been dropped")
138            .close();
139    }
140
141    /// Drops the receiver endpoint of [`ClientRequest`]s, forcefully closing the channel.
142    ///
143    /// The remote peer that would receive the requests is mocked for testing.
144    pub fn drop_outbound_client_request_receiver(&mut self) {
145        self.client_request_receiver
146            .take()
147            .expect("request receiver endpoint has already been dropped");
148    }
149
150    /// Receives a request with production response handling for cross-crate consumer tests.
151    pub fn take_request(&mut self) -> Option<ReceivedClientRequest> {
152        self.try_to_receive_outbound_client_request()
153            .request()
154            .map(|request| ReceivedClientRequest(request.into()))
155    }
156
157    /// Tries to receive a [`ClientRequest`] sent by the [`Client`] instance.
158    ///
159    /// The remote peer that would receive the requests is mocked for testing.
160    pub(crate) fn try_to_receive_outbound_client_request(&mut self) -> ReceiveRequestAttempt {
161        let receive_result = self
162            .client_request_receiver
163            .as_mut()
164            .expect("request receiver endpoint has been dropped")
165            .try_recv();
166
167        match receive_result {
168            Ok(request) => ReceiveRequestAttempt::Request(request),
169            Err(mpsc::TryRecvError::Closed) => ReceiveRequestAttempt::Closed,
170            Err(mpsc::TryRecvError::Empty) => ReceiveRequestAttempt::Empty,
171        }
172    }
173
174    /// Returns the current error in the [`ErrorSlot`], if there is one.
175    pub fn current_error(&self) -> Option<SharedPeerError> {
176        self.error_slot.try_get_error()
177    }
178
179    /// Sets the error in the [`ErrorSlot`], assuming there isn't one already.
180    ///
181    /// # Panics
182    ///
183    /// If there's already an error in the [`ErrorSlot`].
184    pub fn set_error(&self, error: impl Into<SharedPeerError>) {
185        self.error_slot
186            .try_update_error(error.into())
187            .expect("unexpected earlier error in error slot")
188    }
189
190    /// Stops the mock background task that handles incoming remote requests and replies.
191    pub async fn stop_connection_task(&self) {
192        self.connection_aborter.abort();
193
194        // Allow the task to detect that it was aborted.
195        tokio::task::yield_now().await;
196    }
197
198    /// Stops the mock background task that sends periodic heartbeats.
199    pub async fn stop_heartbeat_task(&self) {
200        self.heartbeat_aborter.abort();
201
202        // Allow the task to detect that it was aborted.
203        tokio::task::yield_now().await;
204    }
205}
206
207/// The result of an attempt to receive a [`ClientRequest`] sent by the [`Client`] instance.
208///
209/// The remote peer that would receive the request is mocked for testing.
210// The size disparity between the empty `Closed`/`Empty` variants and the
211// request-carrying variant is intrinsic to this test helper, which is only
212// constructed once per receive attempt.
213#[allow(clippy::large_enum_variant)]
214pub(crate) enum ReceiveRequestAttempt {
215    /// The [`Client`] instance has closed the sender endpoint of the channel.
216    Closed,
217
218    /// There were no queued requests in the channel.
219    Empty,
220
221    /// One request was successfully received.
222    Request(ClientRequest),
223}
224
225impl ReceiveRequestAttempt {
226    /// Check if the attempt to receive resulted in discovering that the sender endpoint had been
227    /// closed.
228    pub fn is_closed(&self) -> bool {
229        matches!(self, ReceiveRequestAttempt::Closed)
230    }
231
232    /// Check if the attempt to receive resulted in no requests.
233    pub fn is_empty(&self) -> bool {
234        matches!(self, ReceiveRequestAttempt::Empty)
235    }
236
237    /// Returns the received request, if there was one.
238    #[allow(dead_code)]
239    pub fn request(self) -> Option<ClientRequest> {
240        match self {
241            ReceiveRequestAttempt::Request(request) => Some(request),
242            ReceiveRequestAttempt::Closed | ReceiveRequestAttempt::Empty => None,
243        }
244    }
245}
246
247/// A builder for a [`Client`] and [`ClientTestHarness`] instance.
248///
249/// Mocked data is used to construct a real [`Client`] instance. The mocked data is initialized by
250/// the [`ClientTestHarnessBuilder`], and can be accessed and changed through the
251/// [`ClientTestHarness`].
252pub struct ClientTestHarnessBuilder<C = future::Ready<()>, H = future::Ready<()>> {
253    connection_task: Option<C>,
254    heartbeat_task: Option<H>,
255    version: Option<Version>,
256    services: Option<PeerServices>,
257    connected_addr: Option<ConnectedAddr>,
258    start_height: Option<Height>,
259}
260
261impl<C, H> ClientTestHarnessBuilder<C, H>
262where
263    C: Future<Output = ()> + Send + 'static,
264    H: Future<Output = ()> + Send + 'static,
265{
266    /// Configure the mocked version for the peer.
267    pub fn with_version(mut self, version: Version) -> Self {
268        self.version = Some(version);
269        self
270    }
271
272    /// Configure the mocked services the peer advertised in its `version` message.
273    pub fn with_services(mut self, services: PeerServices) -> Self {
274        self.services = Some(services);
275        self
276    }
277
278    /// Configure the mocked connection address metadata for the peer.
279    pub fn with_connected_addr(mut self, connected_addr: ConnectedAddr) -> Self {
280        self.connected_addr = Some(connected_addr);
281        self
282    }
283
284    /// Configure the peer's advertised handshake height.
285    pub fn with_start_height(mut self, start_height: Height) -> Self {
286        self.start_height = Some(start_height);
287        self
288    }
289
290    /// Configure the mock connection task future to use.
291    pub fn with_connection_task<NewC>(
292        self,
293        connection_task: NewC,
294    ) -> ClientTestHarnessBuilder<NewC, H> {
295        ClientTestHarnessBuilder {
296            connection_task: Some(connection_task),
297            heartbeat_task: self.heartbeat_task,
298            version: self.version,
299            services: self.services,
300            connected_addr: self.connected_addr,
301            start_height: self.start_height,
302        }
303    }
304
305    /// Configure the mock heartbeat task future to use.
306    pub fn with_heartbeat_task<NewH>(
307        self,
308        heartbeat_task: NewH,
309    ) -> ClientTestHarnessBuilder<C, NewH> {
310        ClientTestHarnessBuilder {
311            connection_task: self.connection_task,
312            heartbeat_task: Some(heartbeat_task),
313            version: self.version,
314            services: self.services,
315            connected_addr: self.connected_addr,
316            start_height: self.start_height,
317        }
318    }
319
320    /// Build a [`Client`] instance with the mocked data and a [`ClientTestHarness`] to track it.
321    pub fn finish(self) -> (Client, ClientTestHarness) {
322        let (shutdown_sender, shutdown_receiver) = oneshot::channel();
323        let (client_request_sender, client_request_receiver) = mpsc::channel(1);
324        let (block_advert_tx, block_advert_receiver) = tokio::sync::mpsc::channel(4);
325
326        let error_slot = ErrorSlot::default();
327        let remote_version = self.version.unwrap_or(Version(0));
328
329        let (connection_task, connection_aborter) =
330            Self::spawn_background_task_or_fallback(self.connection_task);
331        let (heartbeat_task, heartbeat_aborter) =
332            Self::spawn_background_task_or_fallback_with_result(self.heartbeat_task);
333
334        let negotiated_version =
335            std::cmp::min(remote_version, constants::CURRENT_NETWORK_PROTOCOL_VERSION);
336
337        let remote = VersionMessage {
338            version: remote_version,
339            services: self.services.unwrap_or_default(),
340            timestamp: Utc::now(),
341            address_recv: AddrInVersion::new(
342                SocketAddrV4::new(Ipv4Addr::LOCALHOST, 1),
343                PeerServices::default(),
344            ),
345            address_from: AddrInVersion::new(
346                SocketAddrV4::new(Ipv4Addr::LOCALHOST, 2),
347                PeerServices::default(),
348            ),
349            nonce: Nonce::default(),
350            user_agent: "client test harness".to_string(),
351            start_height: self.start_height.unwrap_or(Height(0)),
352            relay: true,
353        };
354
355        let connection_info = Arc::new(ConnectionInfo {
356            connected_addr: self.connected_addr.unwrap_or(ConnectedAddr::Isolated),
357            negotiated_version,
358            // A test peer that advertises compact block relay has negotiated it.
359            early_block_relay: remote.services.contains(PeerServices::NODE_COMPACT_BLOCKS),
360            remote,
361        });
362
363        let client = Client {
364            connection_info,
365            shutdown_tx: Some(shutdown_sender),
366            server_tx: client_request_sender,
367            block_advert_tx,
368            error_slot: error_slot.clone(),
369            connection_task,
370            heartbeat_task,
371        };
372
373        let harness = ClientTestHarness {
374            client_request_receiver: Some(client_request_receiver),
375            block_advert_receiver,
376            shutdown_receiver: Some(shutdown_receiver),
377            error_slot,
378            remote_version,
379            connection_aborter,
380            heartbeat_aborter,
381        };
382
383        (client, harness)
384    }
385
386    /// Spawn a mock background abortable task `task_future` if provided, or a fallback task
387    /// otherwise.
388    ///
389    /// The fallback task stays alive until explicitly aborted.
390    fn spawn_background_task_or_fallback<T>(task_future: Option<T>) -> (JoinHandle<()>, AbortHandle)
391    where
392        T: Future<Output = ()> + Send + 'static,
393    {
394        match task_future {
395            Some(future) => Self::spawn_background_task(future),
396            None => Self::spawn_background_task(future::pending()),
397        }
398    }
399
400    /// Spawn a mock background abortable task to run `task_future`.
401    fn spawn_background_task<T>(task_future: T) -> (JoinHandle<()>, AbortHandle)
402    where
403        T: Future<Output = ()> + Send + 'static,
404    {
405        let (task, abort_handle) = future::abortable(task_future);
406        let task_handle = tokio::spawn(task.map(|_result| ()));
407
408        (task_handle, abort_handle)
409    }
410
411    // TODO: In the context of #4734:
412    // - Delete `spawn_background_task_or_fallback` and `spawn_background_task`
413    // - Rename `spawn_background_task_or_fallback_with_result` and `spawn_background_task_with_result` to
414    //   `spawn_background_task_or_fallback` and `spawn_background_task`
415
416    // Similar to `spawn_background_task_or_fallback` but returns a `Result`.
417    fn spawn_background_task_or_fallback_with_result<T>(
418        task_future: Option<T>,
419    ) -> (JoinHandle<Result<(), BoxError>>, AbortHandle)
420    where
421        T: Future<Output = ()> + Send + 'static,
422    {
423        match task_future {
424            Some(future) => Self::spawn_background_task_with_result(future),
425            None => Self::spawn_background_task_with_result(future::pending()),
426        }
427    }
428
429    // Similar to `spawn_background_task` but returns a `Result`.
430    fn spawn_background_task_with_result<T>(
431        task_future: T,
432    ) -> (JoinHandle<Result<(), BoxError>>, AbortHandle)
433    where
434        T: Future<Output = ()> + Send + 'static,
435    {
436        let (task, abort_handle) = future::abortable(task_future);
437        let task_handle = tokio::spawn(task.map(|_result| Ok(())));
438
439        (task_handle, abort_handle)
440    }
441}