use std::{collections::HashSet, future::Future, sync::Arc};
use futures::{channel::mpsc, SinkExt};
use zebra_chain::serialization::SerializationError;
use zebra_test::mock_service::{MockService, PanicAssertion};
use crate::{
constants::REQUEST_TIMEOUT,
peer::{register_inventory_status, Connection, ErrorSlot},
peer_set::{inventory_registry::RepeatRequests, ActiveConnectionCounter},
protocol::{external::Message, internal::InventoryResponse},
};
use super::*;
fn block_download() -> (Request, InventoryHash, Response) {
let block: block::Block = zebra_test::vectors::BLOCK_MAINNET_10_BYTES
.zcash_deserialize_into()
.expect("the historical block vector is valid");
let hash = block::Hash::from(&block);
(
Request::BlocksByHash(iter::once(hash).collect()),
InventoryHash::Block(hash),
Response::Blocks(vec![InventoryResponse::Available((Arc::new(block), None))]),
)
}
async fn finish_download(
handle: &mut ClientTestHarness,
request: Request,
response: Response,
response_fut: impl Future<Output = Result<Response, BoxError>>,
) {
let client_request = handle
.try_to_receive_outbound_client_request()
.request()
.expect("the eligible peer must receive the download before its queue deadline");
assert_eq!(client_request.request, request);
client_request
.tx
.send(Ok(response.clone()))
.expect("the download is still waiting for its response");
assert_eq!(
timeout(INVENTORY_BUSY_PEER_WAIT_TIMEOUT, response_fut)
.await
.expect("a dispatched download must not hang")
.expect("the peer returned the requested block"),
response,
);
}
#[tokio::test(start_paused = true)]
async fn carried_advertiser_respects_missing_and_failed_candidates() {
let _init_guard = zebra_test::init();
for failed in [false, true] {
let (mut peer_set, mut guard, addrs, mut handles, _best_tip) =
peer_set_with_services(&SERVING_AND_NON_SERVING);
let (_, inventory, response) = block_download();
let InventoryHash::Block(hash) = inventory else {
unreachable!("the helper constructs block inventory");
};
let request = Request::BlockDownload {
hash,
advertiser: Some(addrs[1]),
};
if failed {
assert!(respond_to_request(
&mut peer_set,
&mut handles[1],
request.clone(),
Err(PeerError::ConnectionReceiveTimeout.into()),
)
.await
.is_err());
} else {
send_inventory(
&mut guard,
InventoryStatus::new_missing(inventory, addrs[1]),
);
}
let download = peer_set
.ready()
.await
.expect("the healthy serving connection remains ready")
.call(request.clone());
assert_eq!(
received_request(&mut handles[1]),
None,
"known provenance must not restore an ineligible source",
);
finish_download(&mut handles[0], request, response, download).await;
}
}
#[tokio::test(start_paused = true)]
async fn failed_advertiser_does_not_enable_nonserving_fallback() {
let _init_guard = zebra_test::init();
let (mut peer_set, mut guard, addrs, mut handles, _best_tip) = peer_set_with_services(&[
PeerServices::NODE_NETWORK,
PeerServices::empty(),
PeerServices::empty(),
]);
let (request, hash, response) = block_download();
send_inventory(&mut guard, InventoryStatus::new_available(hash, addrs[1]));
assert!(respond_to_request(
&mut peer_set,
&mut handles[1],
request.clone(),
Err(PeerError::ConnectionReceiveTimeout.into()),
)
.await
.is_err());
let _busy_futs = make_serving_peer_busy(&mut peer_set, addrs[0]).await;
assert!(peer_set.has_peer_with_addr(addrs[1]));
assert!(peer_set
.inventory_registry
.failed_peers(hash)
.any(|p| *p == addrs[1]));
let mut queued = peer_set
.ready()
.await
.expect("fallback peers are ready")
.call(request.clone());
assert!(timeout(INVENTORY_BUSY_PEER_WAIT_TIMEOUT / 4, &mut queued)
.await
.is_err());
assert_eq!(received_request(&mut handles[1]), None);
assert_eq!(
received_request(&mut handles[2]),
None,
"the failed advertisement must not enable a non-serving fallback",
);
assert_eq!(received_request(&mut handles[0]), Some(block_request(1)));
assert_eq!(received_request(&mut handles[0]), Some(block_request(9)));
timeout(INVENTORY_BUSY_PEER_WAIT_TIMEOUT / 4, peer_set.ready())
.await
.expect("released client capacity must become ready")
.expect("the peer set remains healthy");
finish_download(&mut handles[0], request, response, queued).await;
}
#[derive(Clone, Copy)]
enum CandidateChange {
Failure,
Removal,
Advertisement,
}
async fn queued_block_reroutes_on_candidate_change(change: CandidateChange) {
let _init_guard = zebra_test::init();
let (initial_peers, addrs, mut handles) = mock_peers_with_services(&SERVING_AND_NON_SERVING);
let (mut discovery_tx, discovery_rx) = mpsc::channel(2);
let (minimum_peer_version, _best_tip) =
MinimumPeerVersion::with_mock_chain_tip(&Network::Mainnet);
let (mut peer_set, mut guard) = PeerSetBuilder::new()
.with_discover(stream::select(initial_peers, discovery_rx))
.with_minimum_peer_version(minimum_peer_version)
.max_conns_per_ip(max(SERVING_AND_NON_SERVING.len(), DEFAULT_MAX_CONNS_PER_IP))
.build();
let (request, hash, response) = block_download();
let first_response = peer_set
.ready()
.await
.expect("serving peer is ready")
.call(request.clone());
let first_request = handles[0]
.try_to_receive_outbound_client_request()
.request()
.expect("the serving peer receives the original download");
assert_eq!(first_request.request, request);
let _busy_futs = make_serving_peer_busy(&mut peer_set, addrs[0]).await;
let (mut peer_set, poll_task) = peer_set.into_buffer(10);
let mut queued = peer_set
.ready()
.await
.expect("the buffer has room")
.call(request.clone());
assert!(timeout(INVENTORY_BUSY_PEER_WAIT_TIMEOUT / 4, &mut queued)
.await
.is_err());
assert_eq!(received_request(&mut handles[1]), None);
match change {
CandidateChange::Failure => {
first_request
.tx
.send(Err(PeerError::ConnectionReceiveTimeout.into()))
.expect("the original download is still waiting");
timeout(INVENTORY_BUSY_PEER_WAIT_TIMEOUT / 4, first_response)
.await
.expect("the real client must deliver its error")
.expect_err("the original download failed");
}
CandidateChange::Removal => {
discovery_tx
.try_send(Ok(Change::Remove(addrs[0])))
.expect("the discovery channel has room");
}
CandidateChange::Advertisement => {
send_inventory(&mut guard, InventoryStatus::new_available(hash, addrs[1]));
}
}
tokio::time::sleep(INVENTORY_BUSY_PEER_WAIT_TIMEOUT / 4).await;
finish_download(&mut handles[1], request, response, queued).await;
poll_task.abort();
}
#[tokio::test(start_paused = true)]
async fn queued_block_reroutes_on_failure_behind_buffer() {
queued_block_reroutes_on_candidate_change(CandidateChange::Failure).await;
}
#[tokio::test(start_paused = true)]
async fn queued_block_reroutes_on_removal_behind_buffer() {
queued_block_reroutes_on_candidate_change(CandidateChange::Removal).await;
}
#[tokio::test(start_paused = true)]
async fn queued_block_reroutes_on_advertisement_behind_buffer() {
queued_block_reroutes_on_candidate_change(CandidateChange::Advertisement).await;
}
#[tokio::test(start_paused = true)]
async fn caller_drop_does_not_record_block_failure() {
let _init_guard = zebra_test::init();
let (mut peer_set, _guard, addrs, mut handles, _best_tip) =
peer_set_with_services(&SERVING_AND_NON_SERVING);
let (request, hash, response) = block_download();
let mut pending = peer_set
.ready()
.await
.expect("serving peer is ready")
.call(request.clone());
let in_flight = handles[0]
.try_to_receive_outbound_client_request()
.request()
.expect("the serving peer received the download");
assert!(pending.as_mut().now_or_never().is_none());
drop(pending);
assert!(in_flight.tx.is_canceled());
peer_set
.ready()
.await
.expect("caller cancellation leaves the peer usable");
assert_eq!(peer_set.inventory_registry.failed_peers(hash).count(), 0);
assert_eq!(peer_set.inventory_registry.missing_peers(hash).count(), 0);
assert!(peer_set.has_peer_with_addr(addrs[0]));
let retry = peer_set.call(request.clone());
assert_eq!(received_request(&mut handles[1]), None);
finish_download(&mut handles[0], request, response, retry).await;
}
async fn connection_block_error_attribution(not_found: bool) {
let _init_guard = zebra_test::init();
let (mut peer_set, mut guard, addrs, mut handles, _best_tip) =
peer_set_with_services(&SERVING_AND_NON_SERVING);
let (request, hash, response) = block_download();
peer_set.ready().await.expect("serving peer is ready");
let connection_info = peer_set.ready_services[&addrs[0]].connection_info().clone();
let pending = peer_set.call(request.clone());
let client_request = handles[0]
.try_to_receive_outbound_client_request()
.request()
.expect("the serving client received the download");
let inv_collector = guard.inventory_sender().as_ref().unwrap().clone();
let connected_addr = crate::peer::ConnectedAddr::new_inbound_direct(addrs[0]);
let (mut client_tx, client_rx) = mpsc::channel(1);
let (_advert_tx, advert_rx) = tokio::sync::mpsc::channel(1);
let (mut remote_tx, remote_rx) = mpsc::channel(1);
let (outbound_tx, mut outbound_rx) = mpsc::channel(1);
let inbound: MockService<Request, Response, PanicAssertion> = MockService::build().finish();
let connection = Connection::new(
inbound,
(
client_rx,
advert_rx,
peer_set.minimum_peer_version.clone(),
peer_set.bans_receiver.clone(),
),
ErrorSlot::default(),
outbound_tx.sink_map_err(|_| {
SerializationError::from(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"test peer message receiver closed",
))
}),
ActiveConnectionCounter::new_counter().track_connection(),
connection_info,
Vec::new(),
);
let remote_rx = remote_rx
.then(move |msg| register_inventory_status(msg, connected_addr, inv_collector.clone()));
let connection_task = tokio::spawn(connection.run(remote_rx.boxed()));
client_tx
.try_send(client_request)
.expect("the client channel has room");
assert_eq!(
timeout(REQUEST_TIMEOUT / 4, outbound_rx.next())
.await
.expect("the connection must send getdata before its response timeout"),
Some(Message::GetData(vec![hash])),
);
if not_found {
remote_tx
.try_send(Ok(Message::NotFound(vec![hash])))
.expect("the peer response channel has room");
}
let error = timeout(REQUEST_TIMEOUT + Duration::from_secs(1), pending)
.await
.expect("the production response deadline must complete the request")
.expect_err("the peer either refused the block or timed out");
let error = error
.downcast_ref::<SharedPeerError>()
.expect("client errors retain their type");
if not_found {
assert!(error.inner_debug().contains("NotFoundResponse"));
} else {
assert_eq!(error.inner_debug(), "ConnectionReceiveTimeout");
}
peer_set
.ready()
.await
.expect("the fallback peer remains ready");
assert_eq!(
peer_set
.inventory_registry
.missing_peers(hash)
.copied()
.collect::<Vec<_>>(),
if not_found { vec![addrs[0]] } else { vec![] },
);
assert_eq!(
peer_set
.inventory_registry
.failed_peers(hash)
.copied()
.collect::<Vec<_>>(),
if not_found { vec![] } else { vec![addrs[0]] },
);
let retry = peer_set.call(request.clone());
assert_eq!(received_request(&mut handles[0]), None);
finish_download(&mut handles[1], request, response, retry).await;
connection_task.abort();
}
#[tokio::test(start_paused = true)]
async fn explicit_notfound_records_missing_without_block_failure() {
connection_block_error_attribution(true).await;
}
#[tokio::test(start_paused = true)]
async fn connection_timeout_records_block_failure_without_missing() {
connection_block_error_attribution(false).await;
}
#[tokio::test(start_paused = true)]
async fn busy_failed_nonserving_peer_remains_last_resort() {
let _init_guard = zebra_test::init();
let (mut peer_set, mut guard, addrs, mut handles, _best_tip) =
peer_set_with_services(&[PeerServices::empty(), PeerServices::empty()]);
let (request, hash, response) = block_download();
send_inventory(&mut guard, InventoryStatus::new_missing(hash, addrs[1]));
assert!(respond_to_request(
&mut peer_set,
&mut handles[0],
request.clone(),
Err(PeerError::ConnectionReceiveTimeout.into()),
)
.await
.is_err());
let mut busy = Vec::new();
for byte in [1, 9] {
send_inventory(
&mut guard,
InventoryStatus::new_available(InventoryHash::Block(block::Hash([byte; 32])), addrs[0]),
);
busy.push(
peer_set
.ready()
.await
.expect("a peer is ready")
.call(block_request(byte)),
);
}
peer_set
.ready()
.await
.expect("the missing peer is still ready");
assert!(peer_set.cancel_handles.contains_key(&addrs[0]));
let mut queued = peer_set.call(request.clone());
assert!(
timeout(INVENTORY_BUSY_PEER_WAIT_TIMEOUT / 4, &mut queued)
.await
.is_err(),
"the only non-missing peer must be awaited rather than immediately refused",
);
assert_eq!(received_request(&mut handles[1]), None);
assert_eq!(received_request(&mut handles[0]), Some(block_request(1)));
assert_eq!(received_request(&mut handles[0]), Some(block_request(9)));
timeout(INVENTORY_BUSY_PEER_WAIT_TIMEOUT / 4, peer_set.ready())
.await
.expect("released client capacity must become ready")
.expect("the peer set remains healthy");
finish_download(&mut handles[0], request, response, queued).await;
}
#[derive(Clone, Copy)]
enum ReplacementFailure {
Current,
Previous,
Delayed,
}
async fn replacement_connection_ignores_old_failure(failure: ReplacementFailure) {
let _init_guard = zebra_test::init();
let (initial_peers, addrs, mut handles) = mock_peers_with_services(&SERVING_AND_NON_SERVING);
let (mut discovery_tx, discovery_rx) = mpsc::channel(2);
let (minimum_peer_version, _best_tip) =
MinimumPeerVersion::with_mock_chain_tip(&Network::Mainnet);
let (mut peer_set, _guard) = PeerSetBuilder::new()
.with_discover(stream::select(initial_peers, discovery_rx))
.with_minimum_peer_version(minimum_peer_version)
.max_conns_per_ip(max(SERVING_AND_NON_SERVING.len(), DEFAULT_MAX_CONNS_PER_IP))
.build();
let (request, hash, response) = block_download();
let old_response = peer_set
.ready()
.await
.expect("old connection is ready")
.call(request.clone());
let old_request = handles[0]
.try_to_receive_outbound_client_request()
.request()
.expect("the old connection receives the download");
let delayed = if matches!(failure, ReplacementFailure::Delayed) {
Some((old_response, old_request))
} else {
old_request
.tx
.send(Err(PeerError::ConnectionReceiveTimeout.into()))
.expect("the old request is waiting for its response");
timeout(INVENTORY_BUSY_PEER_WAIT_TIMEOUT, old_response)
.await
.expect("the old response must not hang")
.expect_err("the old connection failed");
peer_set.ready().await.expect("fallback remains ready");
assert_eq!(
peer_set
.inventory_registry
.failed_peers(hash)
.copied()
.collect::<Vec<_>>(),
vec![addrs[0]]
);
if matches!(failure, ReplacementFailure::Previous) {
tokio::time::advance(crate::constants::INVENTORY_ROTATION_INTERVAL).await;
peer_set
.ready()
.await
.expect("rotation leaves connected peers usable");
}
None
};
let (replacement, mut replacement_handle) = ClientTestHarness::build()
.with_version(CURRENT_NETWORK_PROTOCOL_VERSION)
.with_services(PeerServices::NODE_NETWORK)
.finish();
discovery_tx
.try_send(Ok(Change::Remove(addrs[0])))
.expect("the discovery channel has room");
discovery_tx
.try_send(Ok(Change::Insert(addrs[0], replacement.into())))
.expect("the discovery channel has room for the replacement");
timeout(INVENTORY_BUSY_PEER_WAIT_TIMEOUT, peer_set.ready())
.await
.expect("the replacement must become ready")
.expect("the peer set remains healthy");
assert!(!handles[0].wants_connection_heartbeats());
if let Some((old_response, old_request)) = delayed {
old_request
.tx
.send(Err(PeerError::ConnectionReceiveTimeout.into()))
.expect("the old request still owns its response receiver");
timeout(INVENTORY_BUSY_PEER_WAIT_TIMEOUT, old_response)
.await
.expect("the delayed response must not hang")
.expect_err("the old request failed");
peer_set
.ready()
.await
.expect("the replacement remains ready");
}
let retry = peer_set.call(request.clone());
assert_eq!(
received_request(&mut handles[1]),
None,
"the replacement must not lose serving preference to its predecessor's failure",
);
finish_download(&mut replacement_handle, request, response, retry).await;
assert_eq!(peer_set.inventory_registry.failed_peers(hash).count(), 0);
}
#[tokio::test(start_paused = true)]
async fn replacement_connection_does_not_inherit_cached_block_failure() {
for failure in [ReplacementFailure::Current, ReplacementFailure::Previous] {
replacement_connection_ignores_old_failure(failure).await;
}
}
#[tokio::test(start_paused = true)]
async fn replacement_connection_ignores_delayed_old_block_failure() {
replacement_connection_ignores_old_failure(ReplacementFailure::Delayed).await;
}
#[tokio::test(start_paused = true)]
async fn overdue_inventory_rotations_preserve_new_block_failure() {
let _init_guard = zebra_test::init();
let (mut peer_set, _guard, addrs, mut handles, _best_tip) =
peer_set_with_services(&SERVING_AND_NON_SERVING);
let (request, hash, _) = block_download();
respond_to_request(
&mut peer_set,
&mut handles[0],
request,
Err(PeerError::ConnectionReceiveTimeout.into()),
)
.await
.expect_err("the serving peer failed the block request");
tokio::time::advance(3 * crate::constants::INVENTORY_ROTATION_INTERVAL).await;
for _ in 0..3 {
peer_set.ready().await.expect("fallback remains ready");
}
assert!(
peer_set
.inventory_registry
.failed_peers(hash)
.any(|peer| *peer == addrs[0]),
"missed ticks must not expire a failure registered on the first poll",
);
}
#[tokio::test(start_paused = true)]
async fn repeat_request_for_served_advertised_block_asks_another_peer_first() {
let _init_guard = zebra_test::init();
const REQUESTS: usize = 4;
for advertiser_count in [1, REQUESTS] {
const OTHER_PEERS: usize = 2;
let services = vec![PeerServices::NODE_NETWORK; OTHER_PEERS + advertiser_count];
let (mut peer_set, mut guard, addrs, mut handles, _best_tip) =
peer_set_with_services(&services);
let (_, inventory, response) = block_download();
let InventoryHash::Block(hash) = inventory else {
unreachable!("the helper constructs block inventory");
};
let request = Request::BlockDownload {
hash,
advertiser: None,
};
for advertiser in &addrs[OTHER_PEERS..] {
send_inventory(
&mut guard,
InventoryStatus::new_available(inventory, *advertiser),
);
peer_set.ready().await.expect("the peers are ready");
}
let download = peer_set
.ready()
.await
.expect("the peers are ready")
.call(request.clone());
let first_peer = answer_request(&mut handles, Ok(response.clone()))
.expect("a peer received the first request");
assert!(
first_peer >= OTHER_PEERS,
"the first request must prefer an advertiser, but peer {first_peer} got it",
);
download.await.expect("the advertiser returned a block");
let download = peer_set
.ready()
.await
.expect("the peers are ready")
.call(request.clone());
let second_peer = answer_request(&mut handles, Ok(response.clone()))
.expect("a peer received the first repeat request");
assert!(
second_peer < OTHER_PEERS,
"an advertiser must not get the first repeat request, but peer {second_peer} did, \
with {advertiser_count} advertisers",
);
download.await.expect("the peer returned a block");
peer_set.ready().await.expect("the peers are ready");
assert_eq!(
peer_set
.inventory_registry
.served_peers(inventory)
.collect::<HashSet<_>>(),
HashSet::from([&addrs[first_peer], &addrs[second_peer]]),
"a block from a peer chosen for its advertisement, or returned in a repeat request, \
is recorded",
);
assert_eq!(
peer_set.inventory_registry.repeat_requests(inventory),
RepeatRequests {
advertisers: 0,
other_peers: 1,
},
);
let download = peer_set
.ready()
.await
.expect("the peers are ready")
.call(request.clone());
let third_peer = answer_request(&mut handles, Ok(response.clone()))
.expect("a peer received the second repeat request");
assert!(
third_peer != first_peer && third_peer != second_peer,
"a peer that returned the block must not get it again while another peer might have \
it, but peer {third_peer} did, with {advertiser_count} advertisers",
);
assert_eq!(
third_peer >= OTHER_PEERS,
advertiser_count > 1,
"the second repeat request must prefer another advertiser, but peer {third_peer} got \
it, with {advertiser_count} advertisers",
);
download.await.expect("the peer returned a block");
peer_set.ready().await.expect("the peers are ready");
tokio::time::advance(2 * crate::constants::INVENTORY_ROTATION_INTERVAL).await;
for _ in 0..2 {
peer_set.ready().await.expect("the peers are ready");
tokio::time::advance(crate::constants::INVENTORY_ROTATION_INTERVAL).await;
}
peer_set.ready().await.expect("the peers are ready");
assert_eq!(
peer_set.inventory_registry.served_peers(inventory).count(),
0,
);
assert_eq!(
peer_set.inventory_registry.repeat_requests(inventory),
RepeatRequests::default(),
);
}
}
#[tokio::test(start_paused = true)]
async fn repeat_request_reaches_an_honest_advertiser() {
let _init_guard = zebra_test::init();
const RETRIES: usize = 3;
for not_found in [false, true] {
let honest_advertisers = 1..=3;
let services = vec![PeerServices::NODE_NETWORK; 7];
let (mut peer_set, mut guard, addrs, mut handles, _best_tip) =
peer_set_with_services(&services);
let (_, inventory, response) = block_download();
let InventoryHash::Block(hash) = inventory else {
unreachable!("the helper constructs block inventory");
};
let request = Request::BlockDownload {
hash,
advertiser: None,
};
send_inventory(
&mut guard,
InventoryStatus::new_available(inventory, addrs[0]),
);
peer_set.ready().await.expect("the peers are ready");
let download = peer_set
.ready()
.await
.expect("the peers are ready")
.call(request.clone());
finish_download(&mut handles[0], request.clone(), response.clone(), download).await;
peer_set.ready().await.expect("the peers are ready");
for advertiser in &addrs[honest_advertisers.clone()] {
send_inventory(
&mut guard,
InventoryStatus::new_available(inventory, *advertiser),
);
peer_set.ready().await.expect("the peers are ready");
}
let mut recipients = Vec::new();
for _ in 0..RETRIES {
let download = peer_set
.ready()
.await
.expect("the peers are ready")
.call(request.clone());
let recipient = handles
.iter_mut()
.enumerate()
.find_map(|(index, handle)| {
let client_request =
handle.try_to_receive_outbound_client_request().request()?;
let answer = if honest_advertisers.contains(&index) {
Ok(response.clone())
} else if not_found {
Err(PeerError::NotFoundResponse(vec![inventory]).into())
} else {
Err(PeerError::ConnectionReceiveTimeout.into())
};
let _ = client_request.tx.send(answer);
Some(index)
})
.expect("a peer received the retry");
recipients.push(recipient);
let _ = download.await;
if not_found {
send_inventory(
&mut guard,
InventoryStatus::new_missing(inventory, addrs[recipient]),
);
}
peer_set.ready().await.expect("the peers are ready");
if honest_advertisers.contains(&recipient) {
break;
}
}
assert!(
recipients
.last()
.is_some_and(|recipient| honest_advertisers.contains(recipient)),
"the retries went to peers {recipients:?}, but none of them is an honest advertiser \
(not_found: {not_found})",
);
assert!(
!recipients.contains(&0),
"the peer that returned the block must not get a retry",
);
}
}
fn answer_request(
handles: &mut [ClientTestHarness],
answer: Result<Response, SharedPeerError>,
) -> Option<usize> {
handles.iter_mut().enumerate().find_map(|(index, handle)| {
let client_request = handle.try_to_receive_outbound_client_request().request()?;
client_request
.tx
.send(answer.clone())
.expect("the download is still waiting for its response");
Some(index)
})
}
#[tokio::test(start_paused = true)]
async fn served_block_without_advertisement_keeps_advertiser_preference() {
let _init_guard = zebra_test::init();
let (mut peer_set, mut guard, addrs, mut handles, _best_tip) =
peer_set_with_services(&[PeerServices::NODE_NETWORK, PeerServices::empty()]);
let (_, inventory, response) = block_download();
let InventoryHash::Block(hash) = inventory else {
unreachable!("the helper constructs block inventory");
};
let request = Request::BlockDownload {
hash,
advertiser: None,
};
let download = peer_set
.ready()
.await
.expect("the peers are ready")
.call(request.clone());
finish_download(&mut handles[0], request.clone(), response.clone(), download).await;
peer_set.ready().await.expect("the peers are ready");
assert_eq!(
peer_set.inventory_registry.served_peers(inventory).count(),
0,
);
send_inventory(
&mut guard,
InventoryStatus::new_available(inventory, addrs[1]),
);
let download = peer_set
.ready()
.await
.expect("the peers are ready")
.call(request.clone());
assert_eq!(received_request(&mut handles[0]), None);
finish_download(&mut handles[1], request, response, download).await;
}
#[tokio::test(start_paused = true)]
async fn concurrent_repeats_still_reach_an_honest_advertiser() {
let _init_guard = zebra_test::init();
let honest_advertisers = 1..=3;
let services = vec![PeerServices::NODE_NETWORK; 8];
let (mut peer_set, mut guard, addrs, mut handles, _best_tip) =
peer_set_with_services(&services);
let (_, inventory, response) = block_download();
let InventoryHash::Block(hash) = inventory else {
unreachable!("the helper constructs block inventory");
};
let request = Request::BlockDownload {
hash,
advertiser: None,
};
send_inventory(
&mut guard,
InventoryStatus::new_available(inventory, addrs[0]),
);
peer_set.ready().await.expect("the peers are ready");
let download = peer_set
.ready()
.await
.expect("the peers are ready")
.call(request.clone());
finish_download(&mut handles[0], request.clone(), response.clone(), download).await;
peer_set.ready().await.expect("the peers are ready");
for advertiser in &addrs[honest_advertisers.clone()] {
send_inventory(
&mut guard,
InventoryStatus::new_available(inventory, *advertiser),
);
peer_set.ready().await.expect("the peers are ready");
}
let first = peer_set
.ready()
.await
.expect("the peers are ready")
.call(request.clone());
let second = peer_set
.ready()
.await
.expect("the peers are ready")
.call(request.clone());
let mut recipients = Vec::new();
for (index, handle) in handles.iter_mut().enumerate() {
if let Some(client_request) = handle.try_to_receive_outbound_client_request().request() {
let answer = if honest_advertisers.contains(&index) {
Ok(response.clone())
} else {
Err(PeerError::ConnectionReceiveTimeout.into())
};
let _ = client_request.tx.send(answer);
recipients.push(index);
}
}
let _ = first.await;
let _ = second.await;
assert_eq!(recipients.len(), 2, "both repeat requests were sent");
assert!(
recipients
.iter()
.any(|recipient| honest_advertisers.contains(recipient)),
"the concurrent repeat requests went to peers {recipients:?}, but none of them is an \
honest advertiser",
);
assert!(
recipients.iter().any(|recipient| *recipient > 3),
"the concurrent repeat requests went to peers {recipients:?}, but none of them is a peer \
that didn't advertise the block",
);
}
#[tokio::test(start_paused = true)]
async fn repeat_turn_returns_to_the_group_that_had_no_ready_peer() {
let _init_guard = zebra_test::init();
const OTHER_PEER: usize = 3;
let services = vec![PeerServices::NODE_NETWORK; 4];
let (mut peer_set, mut guard, addrs, mut handles, _best_tip) =
peer_set_with_services(&services);
let (_, inventory, response) = block_download();
let InventoryHash::Block(hash) = inventory else {
unreachable!("the helper constructs block inventory");
};
let request = Request::BlockDownload {
hash,
advertiser: None,
};
send_inventory(
&mut guard,
InventoryStatus::new_available(inventory, addrs[0]),
);
peer_set.ready().await.expect("the peers are ready");
let download = peer_set
.ready()
.await
.expect("the peers are ready")
.call(request.clone());
finish_download(&mut handles[0], request.clone(), response.clone(), download).await;
peer_set.ready().await.expect("the peers are ready");
for advertiser in &addrs[1..OTHER_PEER] {
send_inventory(
&mut guard,
InventoryStatus::new_available(inventory, *advertiser),
);
peer_set.ready().await.expect("the peers are ready");
}
let mut busy = Vec::new();
for byte in [7, 9] {
send_inventory(
&mut guard,
InventoryStatus::new_available(
InventoryHash::Block(block::Hash([byte; 32])),
addrs[OTHER_PEER],
),
);
busy.push(
peer_set
.ready()
.await
.expect("the peers are ready")
.call(block_request(byte)),
);
}
peer_set.ready().await.expect("the advertisers are ready");
assert!(peer_set.cancel_handles.contains_key(&addrs[OTHER_PEER]));
let download = peer_set
.ready()
.await
.expect("the peers are ready")
.call(request.clone());
let first_repeat_peer = answer_request(
&mut handles,
Err(PeerError::ConnectionReceiveTimeout.into()),
)
.expect("a peer received the first repeat request");
assert!(
(1..OTHER_PEER).contains(&first_repeat_peer),
"an advertiser must get the repeat request when no other peer is ready, but peer \
{first_repeat_peer} got it",
);
let _ = download.await;
for _ in 0..busy.len() {
let other_request = handles[OTHER_PEER]
.try_to_receive_outbound_client_request()
.request()
.expect("the busy peer got the other block requests");
let _ = other_request
.tx
.send(Err(PeerError::ConnectionReceiveTimeout.into()));
}
for other_download in busy {
let _ = other_download.await;
}
peer_set.ready().await.expect("the peers are ready");
let download = peer_set
.ready()
.await
.expect("the peers are ready")
.call(request.clone());
let second_repeat_peer = answer_request(
&mut handles,
Err(PeerError::ConnectionReceiveTimeout.into()),
)
.expect("a peer received the second repeat request");
assert_eq!(
second_repeat_peer, OTHER_PEER,
"the group that had no ready peer must get the next repeat request",
);
let _ = download.await;
}