use std::{sync::Arc, time::Duration};
use tokio::sync::Notify;
use futures::StreamExt as _;
use tower::{service_fn, util::BoxCloneService};
use zebra_chain::parameters::Network;
use zebra_test::mock_service::{MockService, PanicAssertion};
use super::*;
#[test]
fn download_verify_error_metric_labels_ignore_details() {
use zebra_consensus::error::TransactionError;
use TransactionDownloadVerifyError::*;
for detail in ["first error detail", "second error detail"] {
assert_eq!(
StateError(BoxError::from(detail).into()).metric_label(),
"state_error",
);
assert_eq!(
DownloadFailed(BoxError::from(detail).into()).metric_label(),
"download_failed",
);
}
for error in [
TransactionError::WrongVersion,
TransactionError::WrongConsensusBranchId,
] {
let error = Invalid {
error,
advertiser_addr: None,
transaction_upgrade: None,
verification_height: Height(0),
};
assert_eq!(error.metric_label(), "invalid");
}
assert_eq!(
NonStandard(NonStandardTransactionError::IsDust).metric_label(),
"non_standard",
);
}
#[tokio::test]
async fn per_peer_cap_applies_to_pushed_transactions() {
let _init_guard = zebra_test::init();
let network = Network::Mainnet;
let source: SocketAddr = "192.168.0.1:8233".parse().expect("valid socket address");
let pushed: Vec<Gossip> = network
.unmined_transactions_in_blocks(1..=10)
.take(MAX_INBOUND_CONCURRENCY_PER_PEER + 1)
.map(|tx| Gossip::Tx(tx.transaction))
.collect();
assert_eq!(
pushed.len(),
MAX_INBOUND_CONCURRENCY_PER_PEER + 1,
"test needs enough distinct transactions to exceed the per-peer cap",
);
let peer_set: MockService<zn::Request, zn::Response, PanicAssertion> =
MockService::build().for_unit_tests();
let verifier: MockService<tx::MempoolRequest, tx::MempoolResponse, PanicAssertion> =
MockService::build().for_unit_tests();
let state: MockService<zs::Request, zs::Response, PanicAssertion> =
MockService::build().for_unit_tests();
let mut downloads = Downloads::new(peer_set, verifier, state, Arc::new(Notify::new()));
for gossip in pushed.iter().take(MAX_INBOUND_CONCURRENCY_PER_PEER) {
downloads
.download_if_needed_and_verify(gossip.clone(), Some(source), None)
.expect("pushes below the per-peer cap are admitted");
}
let result = downloads.download_if_needed_and_verify(
pushed[MAX_INBOUND_CONCURRENCY_PER_PEER].clone(),
Some(source),
None,
);
assert!(
matches!(result, Err(MempoolError::FullQueue)),
"a push exceeding the per-peer cap must be rejected with `FullQueue`, got {result:?}",
);
downloads.cancel_all();
}
#[tokio::test]
async fn pushed_transaction_attributes_invalid_error_to_peer() {
use zebra_consensus::error::TransactionError;
let _init_guard = zebra_test::init();
let network = Network::Mainnet;
let peer_addr: SocketAddr = "203.0.113.7:8233".parse().unwrap();
let transaction = network
.unmined_transactions_in_blocks(1..=1)
.next()
.expect("at least one test transaction")
.transaction;
let transaction_upgrade = transaction.transaction.network_upgrade();
type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
let mut downloads = Downloads::new(
BoxCloneService::new(service_fn(|_request| async move {
panic!("pushed transactions must not be downloaded");
})),
BoxCloneService::new(service_fn(|_request| async move {
Err(Box::new(TransactionError::WrongVersion) as BoxError)
})),
BoxCloneService::new(service_fn(|request| async move {
match request {
zs::Request::Transaction(_) => Ok(zs::Response::Transaction(None)),
zs::Request::Tip => Ok(zs::Response::Tip(None)),
request => Err(format!("unexpected state request: {request:?}").into()),
}
})),
Arc::new(Notify::new()),
);
downloads
.download_if_needed_and_verify(Gossip::Tx(transaction), Some(peer_addr), None)
.expect("download is queued");
let result = tokio::time::timeout(Duration::from_secs(1), downloads.next())
.await
.expect("pushed transaction should complete")
.expect("download stream should yield an item")
.expect("pushed transaction should not time out");
let error = result
.expect_err("invalid pushed transaction should fail verification")
.1;
assert!(
matches!(
error,
TransactionDownloadVerifyError::Invalid {
advertiser_addr: Some(addr),
transaction_upgrade: actual_upgrade,
verification_height: Height(0),
..
} if addr == PeerSocketAddr::from(peer_addr)
&& actual_upgrade == transaction_upgrade
),
"expected the pushed transaction failure to carry its peer, branch, and height, got {error:?}"
);
}
#[tokio::test(start_paused = true)]
async fn completed_batch_keeps_queue_checker_awake() {
let notified = Arc::new(Notify::new());
let mut downloads = Downloads::new(
service_fn(|_| async { Ok(zn::Response::Transactions(Vec::new())) }),
service_fn(|_| std::future::pending::<Result<tx::MempoolResponse, BoxError>>()),
service_fn(|request| async move {
Ok(match request {
zs::Request::Transaction(_) => zs::Response::Transaction(None),
zs::Request::Tip => zs::Response::Tip(None),
_ => unreachable!("downloads only query transactions and the tip"),
})
}),
notified.clone(),
);
for index in 0..MAX_INBOUND_CONCURRENCY {
let mut hash = [0; 32];
hash[..8].copy_from_slice(&u64::try_from(index).unwrap().to_le_bytes());
downloads
.download_if_needed_and_verify(
Gossip::Id(UnminedTxId::Legacy(transaction::Hash(hash))),
None,
None,
)
.unwrap();
}
tokio::time::sleep(Duration::from_millis(1)).await;
assert!(downloads.pending.iter().all(JoinHandle::is_finished));
let before_backstop = super::super::queue_checker::RATE_LIMIT_DELAY / 2;
notified.notify_one();
tokio::time::timeout(before_backstop, async {
let mut completed = 0;
while completed < MAX_INBOUND_CONCURRENCY {
notified.notified().await;
futures::future::poll_fn(|cx| {
while let Poll::Ready(Some(_)) = Pin::new(&mut downloads).poll_next(cx) {
completed += 1;
}
Poll::Ready(())
})
.await;
tokio::task::yield_now().await;
}
})
.await
.expect("queued results must not wait for the five-second backstop");
}
#[tokio::test(start_paused = true)]
async fn failed_download_does_not_wake_queue_checker() {
let notified = Arc::new(Notify::new());
let mut downloads = Downloads::new(
service_fn(|_| async { Ok(zn::Response::Transactions(Vec::new())) }),
service_fn(|_| std::future::pending::<Result<tx::MempoolResponse, BoxError>>()),
service_fn(|request| async move {
Ok(match request {
zs::Request::Transaction(_) => zs::Response::Transaction(None),
zs::Request::Tip => zs::Response::Tip(None),
_ => unreachable!("downloads only query transactions and the tip"),
})
}),
notified.clone(),
);
downloads
.download_if_needed_and_verify(
Gossip::Id(UnminedTxId::Legacy(transaction::Hash([1; 32]))),
None,
None,
)
.expect("an empty downloader has room for one transaction");
tokio::time::sleep(Duration::from_millis(1)).await;
assert!(downloads.pending.iter().all(JoinHandle::is_finished));
assert!(
tokio::time::timeout(Duration::from_millis(1), notified.notified())
.await
.is_err(),
"a failed download must not wake the queue checker",
);
let result = tokio::time::timeout(Duration::from_secs(1), downloads.next())
.await
.expect("the failed download's result is already queued")
.expect("the stream doesn't end while the downloader holds its results sender");
assert!(
matches!(result, Ok(Err(_))),
"the next poll must still collect the failed download, got {result:?}",
);
}
#[tokio::test(start_paused = true)]
async fn full_queue_can_retry_before_completed_task_exits() {
let mut downloads = Downloads::new(
service_fn(|_| std::future::pending::<Result<zn::Response, BoxError>>()),
service_fn(|_| std::future::pending::<Result<tx::MempoolResponse, BoxError>>()),
service_fn(|_| std::future::pending::<Result<zs::Response, BoxError>>()),
Arc::new(Notify::new()),
);
let tx = Network::Mainnet
.unmined_transactions_in_blocks(1..=1)
.next()
.expect("mainnet vectors contain a transaction");
downloads
.download_if_needed_and_verify(tx.transaction.clone().into(), None, None)
.unwrap();
for index in 1..MAX_INBOUND_CONCURRENCY {
let mut hash = [0; 32];
hash[..8].copy_from_slice(&u64::try_from(index).unwrap().to_le_bytes());
downloads
.download_if_needed_and_verify(
Gossip::Id(UnminedTxId::Legacy(transaction::Hash(hash))),
None,
None,
)
.unwrap();
}
let (response, mut receiver) = oneshot::channel();
downloads
.results_sender
.send(Ok(Ok((tx, Vec::new(), Some(Height(0)), Some(response)))))
.unwrap();
let (tx, _, _, response) = tokio::time::timeout(Duration::from_secs(1), downloads.next())
.await
.unwrap()
.unwrap()
.unwrap()
.unwrap();
assert_eq!(downloads.pending.len(), MAX_INBOUND_CONCURRENCY);
assert!(downloads.pending.iter().all(|task| !task.is_finished()));
downloads
.download_if_needed_and_verify(tx.transaction.into(), None, response)
.expect("consuming a result must free its slot before a stale-tip retry");
assert!(matches!(
receiver.try_recv(),
Err(oneshot::error::TryRecvError::Empty)
));
}