zebrad 7.2.0

The Zcash Foundation's independent, consensus-compatible implementation of a Zcash node
//! Fixed test vectors for the mempool transaction downloader.

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",
    );
}

/// A directly pushed full transaction must consume the sending peer's
/// per-peer admission budget, exactly like an advertised transaction ID, so
/// a single peer cannot bypass [`MAX_INBOUND_CONCURRENCY_PER_PEER`] by
/// sending `tx` messages instead of `inv` advertisements.
///
/// Regression test for `GHSA-m9xx-8rcj-vmgp`.
#[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");

    // Distinct full transactions, as if pushed directly by a single peer.
    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",
    );

    // The cap is enforced before any download/verify work, so the services
    // are never actually driven in this test.
    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()));

    // The first `MAX_INBOUND_CONCURRENCY_PER_PEER` pushes from this peer are admitted.
    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");
    }

    // The next push from the same peer exceeds the per-peer cap and is
    // rejected, even though the global queue still has spare capacity.
    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:?}",
    );

    // Don't leave spawned download tasks behind when the runtime shuts down.
    downloads.cancel_all();
}

/// A directly pushed transaction from a peer must keep that peer's address on
/// the `Invalid` verification error, so the mempool can score the peer's
/// misbehavior. Regression test for `GHSA-g7c4-2w6c-cr3r`.
#[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:?}"
    );
}

/// One wake must drain a batch larger than Tokio's cooperative budget, even a batch of failures,
/// which don't wake the queue checker themselves.
#[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();
    }
    // Paused time advances only after every runnable download has finished.
    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;
    // Failed downloads don't wake the queue checker, so this stands in for the mempool request or
    // backstop queue check that collects them.
    notified.notify_one();
    tokio::time::timeout(before_backstop, async {
        let mut completed = 0;
        while completed < MAX_INBOUND_CONCURRENCY {
            notified.notified().await;
            // Like the mempool, drain ready results but return readiness on Pending.
            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");
}

/// A failed download doesn't wake the queue checker, because there is nothing to store or
/// announce. The next mempool request or backstop queue check still collects the failure.
#[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");
    // Paused time advances only after the download has failed, because the peer set returned no
    // transaction.
    tokio::time::sleep(Duration::from_millis(1)).await;
    assert!(downloads.pending.iter().all(JoinHandle::is_finished));

    // A stored wake would make this wait return immediately.
    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:?}",
    );
}

/// Consuming a result frees admission even if its task has not exited.
#[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();
    }

    // Reproduce the interval after sending a result but before its JoinHandle becomes ready.
    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()));

    // The mempool retries this transaction when its verified tip height is stale.
    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)
    ));
}