use std::{
collections::HashSet,
future::Future,
pin::Pin,
sync::Arc,
task::{Context, Poll},
time::Duration,
};
use futures::{
future::{FutureExt, TryFutureExt},
stream::Stream,
};
use tokio::sync::{
oneshot::{self, error::TryRecvError},
Semaphore,
};
use tower::{buffer::Buffer, timeout::Timeout, util::BoxService, Service, ServiceExt};
use zebra_network::{self as zn, PeerSocketAddr};
use zebra_state::{self as zs};
use zebra_chain::{
block::{self, Block},
parameters::{Network, NetworkUpgrade},
serialization::ZcashSerialize,
transaction::UnminedTxId,
transparent,
};
use zebra_consensus::{router::RouterError, VerifyBlockError};
use zebra_network::{
constants::GETDATA_MAX_BLOCK_COUNT, AddressBook, InventoryResponse, MAX_TX_INV_IN_SENT_MESSAGE,
};
use zebra_node_services::mempool;
use crate::BoxError;
use super::sync::BLOCK_VERIFY_TIMEOUT;
use InventoryResponse::*;
mod cached_peer_addr_response;
pub(crate) mod downloads;
use cached_peer_addr_response::CachedPeerAddrResponse;
#[cfg(test)]
mod tests;
use downloads::{Downloads as BlockDownloads, HeightLimitError};
pub const MAX_INBOUND_RESPONSE_TIME: Duration = Duration::from_secs(5);
pub const GETDATA_SENT_BYTES_LIMIT: usize = 1_000_000;
pub const GETDATA_MAX_TRANSACTION_COUNT: usize = MAX_TX_INV_IN_SENT_MESSAGE as usize;
type BlockDownloadPeerSet =
Buffer<BoxService<zn::Request, zn::Response, zn::BoxError>, zn::Request>;
type State = Buffer<BoxService<zs::Request, zs::Response, zs::BoxError>, zs::Request>;
type Mempool = Buffer<BoxService<mempool::Request, mempool::Response, BoxError>, mempool::Request>;
type SemanticBlockVerifier = Buffer<
BoxService<zebra_consensus::Request, block::Hash, RouterError>,
zebra_consensus::Request,
>;
type GossipedBlockDownloads =
BlockDownloads<BlockDownloadPeerSet, Timeout<SemanticBlockVerifier>, State, zs::LatestChainTip>;
pub struct InboundSetupData {
pub address_book: Arc<std::sync::Mutex<AddressBook>>,
pub block_download_peer_set: BlockDownloadPeerSet,
pub block_verifier: SemanticBlockVerifier,
pub mempool: Mempool,
pub state: State,
pub latest_chain_tip: zs::LatestChainTip,
pub misbehavior_sender: tokio::sync::mpsc::Sender<zn::MisbehaviorReport>,
}
#[allow(clippy::large_enum_variant)]
pub enum Setup {
Pending {
full_verify_concurrency_limit: usize,
setup: oneshot::Receiver<InboundSetupData>,
},
Initialized {
cached_peer_addr_response: CachedPeerAddrResponse,
block_downloads: Pin<Box<GossipedBlockDownloads>>,
mempool: Mempool,
state: State,
misbehavior_sender: tokio::sync::mpsc::Sender<zn::MisbehaviorReport>,
},
FailedInit,
FailedRecv {
error: SharedRecvError,
},
}
#[derive(thiserror::Error, Debug, Clone)]
#[error(transparent)]
pub struct SharedRecvError(Arc<TryRecvError>);
impl From<TryRecvError> for SharedRecvError {
fn from(source: TryRecvError) -> Self {
Self(Arc::new(source))
}
}
pub struct Inbound {
setup: Setup,
compact_relay: Option<(Network, zs::ReadStateService)>,
compact_checks: Arc<Semaphore>,
}
impl Inbound {
pub fn new(
full_verify_concurrency_limit: usize,
setup: oneshot::Receiver<InboundSetupData>,
) -> Inbound {
Inbound {
setup: Setup::Pending {
full_verify_concurrency_limit,
setup,
},
compact_relay: None,
compact_checks: Arc::new(Semaphore::new(3)),
}
}
pub fn with_compact_relay(mut self, network: Network, state: zs::ReadStateService) -> Self {
self.compact_relay = Some((network, state));
self
}
fn take_setup(&mut self) -> Setup {
let mut setup = Setup::FailedInit;
std::mem::swap(&mut self.setup, &mut setup);
setup
}
}
impl Service<zn::Request> for Inbound {
type Response = zn::Response;
type Error = zn::BoxError;
type Future =
Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
let result;
self.setup = match self.take_setup() {
Setup::Pending {
full_verify_concurrency_limit,
mut setup,
} => match setup.try_recv() {
Ok(setup_data) => {
let InboundSetupData {
address_book,
block_download_peer_set,
block_verifier,
mempool,
state,
latest_chain_tip,
misbehavior_sender,
} = setup_data;
let cached_peer_addr_response = CachedPeerAddrResponse::new(address_book);
let mut block_downloads = BlockDownloads::new(
full_verify_concurrency_limit,
block_download_peer_set,
Timeout::new(block_verifier, BLOCK_VERIFY_TIMEOUT),
state.clone(),
latest_chain_tip,
);
if let Some((_, read_state)) = &self.compact_relay {
block_downloads = block_downloads.with_read_state(read_state.clone());
}
let block_downloads = Box::pin(block_downloads);
result = Ok(());
Setup::Initialized {
cached_peer_addr_response,
block_downloads,
mempool,
state,
misbehavior_sender,
}
}
Err(TryRecvError::Empty) => {
result = Ok(());
Setup::Pending {
full_verify_concurrency_limit,
setup,
}
}
Err(error @ TryRecvError::Closed) => {
error!(?error, "inbound setup failed");
let error: SharedRecvError = error.into();
result = Err(error.clone().into());
Setup::FailedRecv { error }
}
},
Setup::FailedInit => unreachable!("incomplete previous Inbound initialization"),
Setup::FailedRecv { error } => {
result = Err(error.clone().into());
Setup::FailedRecv { error }
}
Setup::Initialized {
cached_peer_addr_response,
mut block_downloads,
mempool,
state,
misbehavior_sender,
} => {
while let Poll::Ready(Some(result)) = block_downloads.as_mut().poll_next(cx) {
let Err((err, Some(advertiser_addr))) = result else {
continue;
};
let score = if let Some(err) = err.downcast_ref::<RouterError>() {
err.misbehavior_score()
} else if let Some(err) = err.downcast_ref::<VerifyBlockError>() {
err.misbehavior_score()
} else if let Some(err) = err.downcast_ref::<HeightLimitError>() {
err.misbehavior_score()
} else {
continue;
};
if score != 0 {
let reason = if err.is::<HeightLimitError>() {
format!(
"invalid gossiped block: parent header contradicts coinbase height: {err}"
)
} else {
format!("invalid gossiped block: {err}")
};
let _ = misbehavior_sender.try_send(zn::MisbehaviorReport::new(
advertiser_addr,
score,
reason,
));
}
}
result = Ok(());
Setup::Initialized {
cached_peer_addr_response,
block_downloads,
mempool,
state,
misbehavior_sender,
}
}
};
if matches!(self.setup, Setup::FailedInit) {
unreachable!("incomplete Inbound initialization after poll_ready state handling");
}
Poll::Ready(result)
}
#[instrument(name = "inbound", skip(self, req))]
fn call(&mut self, req: zn::Request) -> Self::Future {
let (cached_peer_addr_response, block_downloads, mempool, state) = match &mut self.setup {
Setup::Initialized {
cached_peer_addr_response,
block_downloads,
mempool,
state,
misbehavior_sender: _,
} => (cached_peer_addr_response, block_downloads, mempool, state),
_ => {
if matches!(
req,
zn::Request::CheckCompactHeader(_)
| zn::Request::CompactBlockTransactions(_)
| zn::Request::CheckCompactBlock(_)
| zn::Request::AdvertiseCompactBlock(..)
) {
return async { Err("the inbound service is still starting".into()) }.boxed();
}
debug!("ignoring request from remote peer during setup");
return async { Ok(zn::Response::Nil) }.boxed();
}
};
match req {
req @ (zn::Request::CheckCompactHeader(_) | zn::Request::CompactBlockTransactions(_) | zn::Request::CheckCompactBlock(_)) => {
let Some((network, read_state)) = self.compact_relay.clone() else {
return async { Err("compact relay context is unavailable".into()) }.boxed();
};
let mempool = mempool.clone();
let slots = self.compact_checks.clone();
tokio::time::timeout(
MAX_INBOUND_RESPONSE_TIME,
compact_request(req, network, read_state, mempool, slots),
).map(|result| match result {
Ok(response) => response,
Err(error) => Err(error.into()),
}).boxed()
}
zn::Request::Peers => {
cached_peer_addr_response.try_refresh();
let response = cached_peer_addr_response.value();
async move {
Ok(response)
}.boxed()
}
zn::Request::BlocksByHash(hashes) => {
if hashes.is_empty() {
return async { Ok(zn::Response::Nil) }.boxed();
}
let state = state.clone();
async move {
let mut blocks: Vec<InventoryResponse<(Arc<Block>, Option<PeerSocketAddr>), block::Hash>> = Vec::new();
let mut total_size = 0;
for &hash in hashes.iter().take(GETDATA_MAX_BLOCK_COUNT) {
if total_size >= GETDATA_SENT_BYTES_LIMIT {
break;
}
let response = state.clone().ready().await?.call(zs::Request::Block(hash.into())).await?;
match response {
zs::Response::Block(Some(block)) => {
total_size += block.zcash_serialized_size();
blocks.push(Available((block, None)))
},
zs::Response::Block(None) => blocks.push(Missing(hash)),
_ => unreachable!("wrong response from state"),
}
}
Ok(zn::Response::Blocks(blocks))
}.boxed()
}
zn::Request::TransactionsById(req_tx_ids) => {
if req_tx_ids.is_empty() {
return async { Ok(zn::Response::Nil) }.boxed();
}
let req_tx_ids: HashSet<UnminedTxId> =
if req_tx_ids.len() > GETDATA_MAX_TRANSACTION_COUNT {
req_tx_ids
.into_iter()
.take(GETDATA_MAX_TRANSACTION_COUNT)
.collect()
} else {
req_tx_ids
};
let request = mempool::Request::TransactionsById(req_tx_ids.clone());
mempool.clone().oneshot(request).map_ok(move |resp| {
let mut total_size = 0;
let transactions = match resp {
mempool::Response::Transactions(transactions) => transactions,
_ => unreachable!("Mempool component should always respond to a `TransactionsById` request with a `Transactions` response"),
};
let available_tx_ids: HashSet<UnminedTxId> = transactions.iter().map(|tx| tx.id).collect();
let missing = req_tx_ids.into_iter().filter(|tx_id| !available_tx_ids.contains(tx_id)).map(Missing);
let available = transactions.into_iter().take_while(|tx| {
let within_limit = total_size < GETDATA_SENT_BYTES_LIMIT;
total_size += tx.size;
within_limit
}).map(|tx| Available((tx, None)));
zn::Response::Transactions(available.chain(missing).collect())
}).boxed()
}
zn::Request::FindBlocks { known_blocks, stop } => {
let request = zs::Request::FindBlockHashes { known_blocks, stop };
state.clone().oneshot(request).map_ok(|resp| match resp {
zs::Response::BlockHashes(hashes) if hashes.is_empty() => zn::Response::Nil,
zs::Response::BlockHashes(hashes) => zn::Response::BlockHashes(hashes),
_ => unreachable!("zebra-state should always respond to a `FindBlockHashes` request with a `BlockHashes` response"),
})
.boxed()
}
zn::Request::FindHeaders { known_blocks, stop } => {
let request = zs::Request::FindBlockHeaders { known_blocks, stop };
state.clone().oneshot(request).map_ok(|resp| match resp {
zs::Response::BlockHeaders(headers) => zn::Response::BlockHeaders(headers),
_ => unreachable!("zebra-state should always respond to a `FindBlockHeaders` request with a `BlockHeaders` response"),
})
.boxed()
}
zn::Request::PushTransaction(transaction, sender) => {
let request = match sender {
Some(peer_addr) => mempool::Request::QueueFromPeer {
candidates: vec![transaction.into()],
source: *peer_addr,
},
None => mempool::Request::Queue(vec![transaction.into()]),
};
mempool
.clone()
.oneshot(request)
.map_ok(|_resp| zn::Response::Nil)
.boxed()
}
zn::Request::AdvertiseTransactionIds(transactions, advertiser) => {
let request = match advertiser {
Some(peer_addr) => mempool::Request::QueueFromPeer {
candidates: transactions.into_iter().map(Into::into).collect(),
source: *peer_addr,
},
None => mempool::Request::Queue(
transactions.into_iter().map(Into::into).collect(),
),
};
mempool
.clone()
.oneshot(request)
.map_ok(|_resp| zn::Response::Nil)
.boxed()
}
zn::Request::AdvertiseCompactBlock(hash, advertiser) => {
let admitted = matches!(
block_downloads.download_and_verify(hash, advertiser),
downloads::DownloadAction::AddedToQueue
);
async move {
if admitted {
Ok(zn::Response::Nil)
} else {
Err("compact advertisement was not admitted".into())
}
}.boxed()
}
zn::Request::AdvertiseBlock(hash, advertiser) => {
block_downloads.download_and_verify(hash, advertiser);
async { Ok(zn::Response::Nil) }.boxed()
}
zn::Request::MempoolTransactionIds => {
mempool.clone().oneshot(mempool::Request::TransactionIds).map_ok(|resp| match resp {
mempool::Response::TransactionIds(transaction_ids) => zn::Response::TransactionIds(transaction_ids.into_iter().collect()),
_ => unreachable!("Mempool component should always respond to a `TransactionIds` request with a `TransactionIds` response"),
})
.boxed()
}
zn::Request::Ping(_) => {
unreachable!("ping requests are handled internally");
}
zn::Request::AdvertiseBlockToAll(_) => unreachable!("should always be decoded as `AdvertiseBlock` request"),
zn::Request::BlockDownload { .. } => unreachable!("peers never send outbound block downloads"),
zn::Request::PollPeerSet => unreachable!("peers never send peer set poll requests"),
}
}
}
async fn compact_request(
req: zn::Request,
network: Network,
read_state: zs::ReadStateService,
mempool: Mempool,
slots: Arc<Semaphore>,
) -> Result<zn::Response, BoxError> {
let header_only = matches!(req, zn::Request::CheckCompactHeader(_));
let permit = Arc::new(if header_only {
slots.try_acquire_owned()?
} else {
slots.acquire_owned().await?
});
match req {
zn::Request::CheckCompactHeader(compact)
| zn::Request::CompactBlockTransactions(compact) => {
let checked = compact.clone();
let worker_permit = permit.clone();
let height = tokio::task::spawn_blocking(move || {
let _permit = worker_permit;
screen_compact_header(&checked, &network)
})
.await??;
let response = read_state
.oneshot(zs::ReadRequest::CheckBestTipHeader {
header: compact.header.clone(),
height,
})
.await?;
assert!(matches!(response, zs::ReadResponse::ValidBestTipHeader));
if header_only {
return Ok(zn::Response::Nil);
}
if compact.short_ids.is_empty() {
return Ok(zn::Response::CompactBlockTransactions(Vec::new()));
}
let mempool::Response::TransactionIds(ids) = mempool
.clone()
.oneshot(mempool::Request::TransactionIds)
.boxed()
.await?
else {
unreachable!("transaction ID requests return transaction IDs");
};
let worker_permit = permit.clone();
let ids = tokio::task::spawn_blocking(move || {
let _permit = worker_permit;
compact.matching_ids(ids)
})
.await?;
let mempool::Response::Transactions(transactions) = mempool
.oneshot(mempool::Request::TransactionsById(ids))
.boxed()
.await?
else {
unreachable!("exact transaction lookups return transactions");
};
let bytes = transactions
.iter()
.fold(0usize, |bytes, tx| bytes.saturating_add(tx.size));
if u64::try_from(bytes).unwrap_or(u64::MAX) > block::MAX_BLOCK_BYTES {
return Err("compact candidates exceed the block byte limit".into());
}
Ok(zn::Response::CompactBlockTransactions(transactions))
}
zn::Request::CheckCompactBlock(block) => {
let checked = block.clone();
let worker_permit = permit.clone();
tokio::task::spawn_blocking(move || {
let _permit = worker_permit;
if u64::try_from(checked.zcash_serialized_size()).unwrap_or(u64::MAX)
> block::MAX_BLOCK_BYTES
{
return Err("compact body exceeds the block byte limit".into());
}
zebra_consensus::coinbase_is_first(&checked)?;
let hashes = checked
.transactions
.iter()
.map(|tx| tx.hash())
.collect::<Vec<_>>();
zebra_consensus::merkle_root_validity(&network, &checked, &hashes)?;
Ok::<_, BoxError>(())
})
.await??;
let response = read_state
.oneshot(zs::ReadRequest::CheckBestTipBlockCommitments(block))
.await?;
assert!(matches!(
response,
zs::ReadResponse::ValidBestTipBlockCommitments
));
Ok(zn::Response::Nil)
}
_ => unreachable!("only compact requests enter compact screening"),
}
}
fn screen_compact_header(
compact: &zn::compact::CompactBlock,
network: &Network,
) -> Result<block::Height, BoxError> {
compact.validate()?;
let height = compact.prefilled[0]
.1
.inputs()
.into_iter()
.next()
.and_then(|input| match input {
transparent::Input::Coinbase { height, .. } => Some(height),
_ => None,
})
.ok_or("compact coinbase has no height")?;
if NetworkUpgrade::current(network, height) < NetworkUpgrade::Nu5 {
return Err("compact authentication requires NU5 commitments".into());
}
let hash = compact.block_hash();
let header = &compact.header;
header.time_is_valid_at(chrono::Utc::now(), &height, &hash)?;
if network.disable_pow() {
zebra_consensus::difficulty_threshold_is_valid(header, network, &height, &hash)?;
} else {
zebra_consensus::difficulty_is_valid(header, network, &height, &hash)?;
zebra_consensus::equihash_solution_is_valid(header)?;
}
Ok(height)
}