zebra_network/peer/client/
tests.rs1#![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
37pub struct ClientTestHarness {
39 client_request_receiver: Option<mpsc::Receiver<ClientRequest>>,
40 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
49pub struct ReceivedClientRequest(super::InProgressClientRequest);
51
52impl ReceivedClientRequest {
53 pub fn request(&self) -> &crate::Request {
55 &self.0.request
56 }
57
58 pub fn respond(self, response: Result<crate::Response, SharedPeerError>) {
60 let _ = self.0.tx.send(response);
61 }
62
63 pub fn is_canceled(&self) -> bool {
65 self.0.tx.is_canceled()
66 }
67}
68
69impl ClientTestHarness {
70 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 pub fn remote_version(&self) -> Version {
85 self.remote_version
86 }
87
88 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 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 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 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 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 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 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 pub fn current_error(&self) -> Option<SharedPeerError> {
176 self.error_slot.try_get_error()
177 }
178
179 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 pub async fn stop_connection_task(&self) {
192 self.connection_aborter.abort();
193
194 tokio::task::yield_now().await;
196 }
197
198 pub async fn stop_heartbeat_task(&self) {
200 self.heartbeat_aborter.abort();
201
202 tokio::task::yield_now().await;
204 }
205}
206
207#[allow(clippy::large_enum_variant)]
214pub(crate) enum ReceiveRequestAttempt {
215 Closed,
217
218 Empty,
220
221 Request(ClientRequest),
223}
224
225impl ReceiveRequestAttempt {
226 pub fn is_closed(&self) -> bool {
229 matches!(self, ReceiveRequestAttempt::Closed)
230 }
231
232 pub fn is_empty(&self) -> bool {
234 matches!(self, ReceiveRequestAttempt::Empty)
235 }
236
237 #[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
247pub 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 pub fn with_version(mut self, version: Version) -> Self {
268 self.version = Some(version);
269 self
270 }
271
272 pub fn with_services(mut self, services: PeerServices) -> Self {
274 self.services = Some(services);
275 self
276 }
277
278 pub fn with_connected_addr(mut self, connected_addr: ConnectedAddr) -> Self {
280 self.connected_addr = Some(connected_addr);
281 self
282 }
283
284 pub fn with_start_height(mut self, start_height: Height) -> Self {
286 self.start_height = Some(start_height);
287 self
288 }
289
290 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 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 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 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 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 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 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 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}