Skip to main content

zebra_network/peer_set/set/tests/
consumer.rs

1//! Real buffered peer-set and client-channel fixtures for downstream consumer tests.
2
3use std::{net::SocketAddr, time::Duration};
4
5use futures::{channel::mpsc, stream, StreamExt};
6use tower::{discover::Change, ServiceExt};
7use zebra_chain::{block, chain_tip::mock::MockChainTip, parameters::Network};
8
9use crate::{
10    constants::CURRENT_NETWORK_PROTOCOL_VERSION,
11    peer::{ClientTestHarness, ConnectedAddr, LoadTrackedClient, MinimumPeerVersion},
12    peer_set::InventoryChange,
13    types::{InventoryHash, PeerServices},
14    BlockAdvertiser, BoxError, NetworkService, PeerSocketAddr, Request, Response,
15};
16
17pub use crate::peer::ReceivedClientRequest;
18
19use super::{PeerSetBuilder, PeerSetGuard};
20
21/// Owns a buffered peer set and the remote endpoints of its real client channels.
22pub struct PeerSetHarness {
23    /// The service to pass to the production sync or inbound constructor.
24    pub network: NetworkService,
25    /// The bounded advertiser for this peer set.
26    pub block_advertiser: BlockAdvertiser<MockChainTip>,
27    /// The connected addresses, in the same order as the supplied service flags.
28    pub addrs: Vec<PeerSocketAddr>,
29    peers: Vec<ClientTestHarness>,
30    guard: PeerSetGuard,
31    busy_requests: Vec<super::super::ResponseFuture>,
32    discovery: mpsc::Sender<Result<Change<PeerSocketAddr, LoadTrackedClient>, BoxError>>,
33}
34
35impl PeerSetHarness {
36    /// Constructs real clients, optionally filling one client's two request-channel slots.
37    ///
38    /// Inventory uses the existing one-entry test channel, so two updates without a poll
39    /// deterministically exercise registry lag. No socket or wall-clock timing is involved.
40    pub async fn new(services: &[PeerServices], busy_peer: Option<usize>) -> Self {
41        let mut guard = PeerSetGuard::new();
42        let inventory_receiver = guard.create_inventory_receiver();
43        let mut addrs = Vec::new();
44        let mut peers = Vec::new();
45        let mut changes: Vec<Result<_, BoxError>> = Vec::new();
46        for (index, services) in services.iter().enumerate() {
47            let host = u8::try_from(index + 1).expect("test peer count fits in an IPv4 octet");
48            let addr: PeerSocketAddr = SocketAddr::from(([127, 0, 0, host], 8233)).into();
49            let (client, handle) = ClientTestHarness::build()
50                .with_version(CURRENT_NETWORK_PROTOCOL_VERSION)
51                .with_services(*services)
52                .with_connected_addr(ConnectedAddr::new_inbound_direct(addr))
53                .finish();
54            changes.push(Ok(Change::Insert(addr, client.into())));
55            addrs.push(addr);
56            peers.push(handle);
57        }
58        let (tip, _tip_sender) = MockChainTip::new();
59        let (discovery, discovered) = mpsc::channel(1);
60        let builder = PeerSetBuilder::new()
61            .with_discover(stream::iter(changes).chain(discovered))
62            .with_minimum_peer_version(MinimumPeerVersion::new(tip, &Network::Mainnet));
63        let (mut peer_set, mut peer_guard) = PeerSetBuilder {
64            inv_stream: Some(inventory_receiver),
65            ..builder
66        }
67        .build();
68        // Keep the sender for the channel actually used by this peer set.
69        *peer_guard.inventory_sender() = guard.inventory_sender().take();
70        if !services.is_empty() {
71            peer_set.ready().await.expect("test peers are ready");
72        }
73        let mut busy_requests = Vec::new();
74        if let Some(peer) = busy_peer {
75            for byte in [0xF0, 0xF1] {
76                peer_set.ready().await.expect("test peers remain connected");
77                busy_requests.push(peer_set.call_ready_peer(
78                    addrs[peer],
79                    Request::BlocksByHash([block::Hash([byte; 32])].into_iter().collect()),
80                ));
81            }
82            peer_set
83                .ready()
84                .await
85                .expect("an idle fallback peer remains ready");
86            assert!(peer_set.cancel_handles.contains_key(&addrs[peer]));
87        }
88        let block_advertiser = peer_set.block_advertiser();
89        let (network, _poll_task) = peer_set.into_buffer(3);
90        Self {
91            network,
92            block_advertiser,
93            addrs,
94            peers,
95            guard: peer_guard,
96            busy_requests,
97            discovery,
98        }
99    }
100
101    /// Discovers another real client without issuing an ordinary network request.
102    pub fn connect_peer(&mut self, services: PeerServices) -> usize {
103        let peer = self.peers.len();
104        let host = u8::try_from(peer + 1).expect("test peer count fits in an IPv4 octet");
105        let addr: PeerSocketAddr = SocketAddr::from(([127, 0, 0, host], 8233)).into();
106        let (client, handle) = ClientTestHarness::build()
107            .with_version(CURRENT_NETWORK_PROTOCOL_VERSION)
108            .with_services(services)
109            .with_connected_addr(ConnectedAddr::new_inbound_direct(addr))
110            .finish();
111        self.discovery
112            .try_send(Ok(Change::Insert(addr, client.into())))
113            .expect("the discovery channel has room for a test peer");
114        self.addrs.push(addr);
115        self.peers.push(handle);
116        peer
117    }
118
119    /// Receives an already-dispatched client request, without advancing the clock.
120    pub fn take_request(&mut self, peer: usize) -> Option<ReceivedClientRequest> {
121        self.peers[peer].take_request()
122    }
123
124    /// Waits at most one virtual second for the specified client to receive a request.
125    pub async fn next_request(&mut self, peer: usize) -> ReceivedClientRequest {
126        self.next_request_from(&[peer]).await.1
127    }
128
129    /// Receives the next request from any of the supplied peers, with a one-second bound.
130    pub async fn next_request_from(&mut self, peers: &[usize]) -> (usize, ReceivedClientRequest) {
131        tokio::time::timeout(Duration::from_secs(1), async {
132            loop {
133                for &peer in peers {
134                    if let Some(request) = self.take_request(peer) {
135                        return (peer, request);
136                    }
137                }
138                tokio::time::sleep(Duration::from_millis(1)).await;
139            }
140        })
141        .await
142        .expect("a selected peer must receive the consumer request")
143    }
144
145    /// Receives a block advert and its write acknowledgment, or none within one virtual second.
146    pub async fn next_block_advert(
147        &mut self,
148        peer: usize,
149    ) -> Option<(
150        block::Hash,
151        tokio::sync::oneshot::Sender<Result<(), BoxError>>,
152    )> {
153        tokio::time::timeout(
154            Duration::from_secs(1),
155            self.peers[peer].block_advert_receiver.recv(),
156        )
157        .await
158        .ok()
159        .flatten()
160        .map(|advert| (advert.hash, advert.result))
161    }
162
163    /// Publishes an inventory event through the real lossy registry channel.
164    pub fn advertise(&mut self, peer: usize, hash: block::Hash) {
165        self.guard
166            .inventory_sender()
167            .as_ref()
168            .unwrap()
169            .send(InventoryChange::new_available(
170                InventoryHash::Block(hash),
171                self.addrs[peer],
172            ))
173            .expect("the real inventory registry is still connected");
174    }
175
176    /// Publishes the missing block inventory explicitly reported by a test peer.
177    pub fn notfound(&mut self, peer: usize, hash: block::Hash) {
178        self.guard
179            .inventory_sender()
180            .as_ref()
181            .unwrap()
182            .send(InventoryChange::new_missing(
183                InventoryHash::Block(hash),
184                self.addrs[peer],
185            ))
186            .expect("the real inventory registry is still connected");
187    }
188
189    /// Polls the production peer set through its normal buffered maintenance request.
190    pub async fn flush(&self) {
191        self.network
192            .clone()
193            .oneshot(Request::PollPeerSet)
194            .await
195            .expect("the test peer set is healthy");
196    }
197
198    /// Frees the two pre-filled client slots and completes their unrelated requests.
199    pub async fn release_busy_peer(&mut self, peer: usize) {
200        for byte in [0xF0, 0xF1] {
201            let request = self.next_request(peer).await;
202            assert_eq!(
203                request.request(),
204                &Request::BlocksByHash([block::Hash([byte; 32])].into_iter().collect()),
205            );
206            request.respond(Ok(Response::Nil));
207        }
208        for response in self.busy_requests.drain(..) {
209            response.await.expect("priming requests completed");
210        }
211    }
212}