#[cfg(test)]
mod tests;
use std::{
collections::{HashMap, HashSet},
net::IpAddr,
pin::Pin,
sync::Arc,
task::{Context, Poll},
time::Duration,
};
use futures::{
future::TryFutureExt,
ready,
stream::{FuturesUnordered, Stream},
};
use indexmap::IndexSet;
use pin_project::pin_project;
use thiserror::Error;
use tokio::{
sync::oneshot,
task::JoinHandle,
time::{sleep, timeout, Instant},
};
use tower::{Service, ServiceExt};
use tracing::Instrument;
use zebra_chain::{
block::{self, Block, HeightDiff},
chain_tip::ChainTip,
parameters::subsidy::SubsidyError,
};
use zebra_consensus::{error::TransactionError, router::RouterError, BlockError, VerifyBlockError};
use zebra_network::{self as zn, PeerSocketAddr};
use zebra_state as zs;
use crate::components::sync::{BLOCK_DOWNLOAD_TIMEOUT, MIN_CONCURRENCY_LIMIT};
type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
const PARENT_LOOKUP_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Copy, Clone, Debug, Error)]
pub enum HeightLimitError {
#[error("gossiped block height {height:?} too far ahead of the tip: {hash:?}")]
AboveLookahead {
height: block::Height,
hash: block::Hash,
},
#[error("gossiped block height {height:?} behind the finalized tip: {hash:?}")]
BehindTip {
height: block::Height,
hash: block::Hash,
},
}
impl HeightLimitError {
pub fn misbehavior_score(&self) -> u32 {
zn::constants::MAX_PEER_MISBEHAVIOR_SCORE
}
}
async fn advertiser_if_parent_contradicts<ZS>(
state: ZS,
parent_hash: block::Hash,
block_height: block::Height,
advertiser_addr: Option<PeerSocketAddr>,
) -> Option<PeerSocketAddr>
where
ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
ZS::Future: Send,
{
let advertiser_addr = advertiser_addr?;
match timeout(
PARENT_LOOKUP_TIMEOUT,
state.oneshot(zs::Request::BlockHeader(parent_hash.into())),
)
.await
{
Ok(Ok(zs::Response::BlockHeader {
height: parent_height,
..
})) if (parent_height + 1) != Some(block_height) => Some(advertiser_addr),
_ => None,
}
}
const EARLY_RELAY_CHECK_TIMEOUT: Duration = Duration::from_secs(5);
const EARLY_RELAY_PARENT_TIMEOUT: Duration = Duration::from_secs(30);
const EARLY_RELAY_PARENT_POLL_INTERVAL: Duration = Duration::from_millis(100);
pub(crate) const MAX_REJECTED_EARLY_BLOCKS: usize = MAX_EARLY_RELAY_ALLOWANCES;
const MAX_EARLY_RELAY_ALLOWANCES: usize = 1_000;
#[derive(Debug, Default)]
pub(crate) struct EarlyRelayAllowances {
used: IndexSet<(IpAddr, block::Hash)>,
}
impl EarlyRelayAllowances {
pub(crate) fn try_use(&mut self, peer: PeerSocketAddr, parent: block::Hash) -> bool {
if !self
.used
.insert((zn::connection_limit_key(peer.ip()), parent))
{
return false;
}
if self.used.len() > MAX_EARLY_RELAY_ALLOWANCES {
self.used.shift_remove_index(0);
}
true
}
}
pub(crate) fn remember_rejected_early_block(
rejected: &mut IndexSet<block::Hash>,
hash: block::Hash,
) {
if rejected.insert(hash) && rejected.len() > MAX_REJECTED_EARLY_BLOCKS {
rejected.shift_remove_index(0);
}
}
#[derive(Debug, Error)]
#[error("block failed later validation after it was authenticated for early relay: {error}")]
pub struct AuthenticatedBlockRejected {
#[source]
error: BoxError,
peer: PeerSocketAddr,
parent: block::Hash,
}
pub(crate) fn is_later_validation_failure(
error: &(dyn std::error::Error + Send + Sync + 'static),
) -> bool {
let error = match error.downcast_ref::<RouterError>() {
Some(RouterError::Block { source }) => source.as_ref(),
Some(RouterError::Checkpoint { .. }) => return false,
None => match error.downcast_ref::<VerifyBlockError>() {
Some(error) => error,
None => return false,
},
};
error.misbehavior_score() != 0
&& match error {
VerifyBlockError::Transaction(_) => true,
VerifyBlockError::Block { source } => matches!(
source,
BlockError::TooManyTransparentSignatureOperations { .. }
| BlockError::Transaction(TransactionError::Subsidy(
SubsidyError::InvalidMinerFees | SubsidyError::Overflow
))
),
VerifyBlockError::Commit(error) => !error.is_auth_commitment_mismatch(),
_ => false,
}
}
async fn best_tip_commitments_are_valid<ZS>(read_state: ZS, block: Arc<Block>) -> bool
where
ZS: zs::ReadState,
{
matches!(
timeout(
EARLY_RELAY_CHECK_TIMEOUT,
read_state.oneshot(zs::ReadRequest::CheckBestTipBlockCommitments(block)),
)
.await,
Ok(Ok(zs::ReadResponse::ValidBestTipBlockCommitments))
)
}
pub(crate) fn start_early_relay_check<ZS, ZSTip>(
read_state: &ZS,
latest_chain_tip: &ZSTip,
block: &Arc<Block>,
) -> Option<JoinHandle<bool>>
where
ZS: zs::ReadState,
ZSTip: ChainTip,
{
(latest_chain_tip.best_tip_hash() == Some(block.header.previous_block_hash)).then(|| {
tokio::spawn(best_tip_commitments_are_valid(
read_state.clone(),
block.clone(),
))
})
}
pub(crate) async fn early_block_is_authenticated<ZS, ZSTip>(
read_state: ZS,
latest_chain_tip: ZSTip,
block: Arc<Block>,
height: block::Height,
early_check: Option<JoinHandle<bool>>,
) -> bool
where
ZS: zs::ReadState,
ZSTip: ChainTip + Send + 'static,
{
let authenticated = match early_check {
Some(early_check) => early_check.await.unwrap_or(false),
None => best_tip_commitments_are_valid(read_state.clone(), block.clone()).await,
};
if authenticated {
return true;
}
let parent = block.header.previous_block_hash;
timeout(EARLY_RELAY_PARENT_TIMEOUT, async move {
let mut retried = false;
loop {
let tip = latest_chain_tip.best_tip_height_and_hash();
match tip {
Some((_, tip_hash)) if tip_hash == parent => {
if retried {
return false;
}
retried = true;
if best_tip_commitments_are_valid(read_state.clone(), block.clone()).await {
return true;
}
}
Some((tip_height, _)) if tip_height >= height => return false,
_ => sleep(EARLY_RELAY_PARENT_POLL_INTERVAL).await,
}
}
})
.await
.unwrap_or(false)
}
pub const MAX_INBOUND_CONCURRENCY: usize = 200;
pub enum DownloadAction {
AddedToQueue,
AlreadyQueued,
FullQueue,
TooManyFromPeer,
AlreadyRejected,
}
#[pin_project]
#[derive(Debug)]
pub struct Downloads<ZN, ZV, ZS, ZSTip>
where
ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
ZN::Future: Send,
ZV: Service<zebra_consensus::Request, Response = block::Hash, Error = BoxError>
+ Send
+ Clone
+ 'static,
ZV::Future: Send,
ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
ZS::Future: Send,
ZSTip: ChainTip + Clone + Send + 'static,
{
full_verify_concurrency_limit: usize,
network: ZN,
verifier: ZV,
state: ZS,
read_state: Option<zs::ReadStateService>,
latest_chain_tip: ZSTip,
#[pin]
pending: FuturesUnordered<
JoinHandle<Result<block::Hash, (BoxError, block::Hash, Option<PeerSocketAddr>)>>,
>,
cancel_handles: HashMap<block::Hash, (oneshot::Sender<()>, Option<IpAddr>)>,
in_flight_ips: HashSet<IpAddr>,
rejected_early_blocks: IndexSet<block::Hash>,
early_relay_allowances: EarlyRelayAllowances,
}
impl<ZN, ZV, ZS, ZSTip> Stream for Downloads<ZN, ZV, ZS, ZSTip>
where
ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
ZN::Future: Send,
ZV: Service<zebra_consensus::Request, Response = block::Hash, Error = BoxError>
+ Send
+ Clone
+ 'static,
ZV::Future: Send,
ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
ZS::Future: Send,
ZSTip: ChainTip + Clone + Send + 'static,
{
type Item = Result<block::Hash, (BoxError, Option<PeerSocketAddr>)>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let this = self.project();
if let Some(join_result) = ready!(this.pending.poll_next(cx)) {
let (result, hash) = match join_result
.expect("block download and verify tasks must not panic")
{
Ok(hash) => (Ok(hash), hash),
Err((e, hash, advertiser_addr)) => match e.downcast::<AuthenticatedBlockRejected>()
{
Ok(rejected) => {
remember_rejected_early_block(this.rejected_early_blocks, hash);
if this
.early_relay_allowances
.try_use(rejected.peer, rejected.parent)
{
debug!(
?hash,
peer = ?rejected.peer,
error = ?rejected.error,
"authenticated early relay block failed later validation: \
rejected it without scoring the peer",
);
let error: BoxError = rejected;
(Err((error, None)), hash)
} else {
debug!(
?hash,
peer = ?rejected.peer,
error = ?rejected.error,
"peer already sent a block on the same parent that failed \
later validation: scoring the peer",
);
let AuthenticatedBlockRejected { error, peer, .. } = *rejected;
(Err((error, Some(peer))), hash)
}
}
Err(e) => (Err((e, advertiser_addr)), hash),
},
};
if let Some((_, Some(ip))) = this.cancel_handles.remove(&hash) {
assert!(
this.in_flight_ips.remove(&ip),
"every tracked IP was inserted when its download was queued",
);
}
Poll::Ready(Some(result))
} else {
Poll::Ready(None)
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.pending.size_hint()
}
}
impl<ZN, ZV, ZS, ZSTip> Downloads<ZN, ZV, ZS, ZSTip>
where
ZN: Service<zn::Request, Response = zn::Response, Error = BoxError> + Send + Clone + 'static,
ZN::Future: Send,
ZV: Service<zebra_consensus::Request, Response = block::Hash, Error = BoxError>
+ Send
+ Clone
+ 'static,
ZV::Future: Send,
ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
ZS::Future: Send,
ZSTip: ChainTip + Clone + Send + 'static,
{
pub fn new(
full_verify_concurrency_limit: usize,
network: ZN,
verifier: ZV,
state: ZS,
latest_chain_tip: ZSTip,
) -> Self {
let full_verify_concurrency_limit =
full_verify_concurrency_limit.clamp(MIN_CONCURRENCY_LIMIT, MAX_INBOUND_CONCURRENCY);
Self {
full_verify_concurrency_limit,
network,
verifier,
state,
read_state: None,
latest_chain_tip,
pending: FuturesUnordered::new(),
cancel_handles: HashMap::new(),
in_flight_ips: HashSet::new(),
rejected_early_blocks: IndexSet::new(),
early_relay_allowances: EarlyRelayAllowances::default(),
}
}
pub fn with_read_state(mut self, read_state: zs::ReadStateService) -> Self {
self.read_state = Some(read_state);
self
}
#[cfg(test)]
pub(super) fn forget_rejected_early_blocks(&mut self) {
self.rejected_early_blocks.clear();
}
#[instrument(skip(self, hash), fields(hash = %hash))]
pub fn download_and_verify(
&mut self,
hash: block::Hash,
advertiser: Option<PeerSocketAddr>,
) -> DownloadAction {
if self.rejected_early_blocks.contains(&hash) {
debug!(
?hash,
"block hash failed later validation after early relay: ignored block",
);
metrics::counter!("gossip.already.rejected.dropped.block.hash.count").increment(1);
return DownloadAction::AlreadyRejected;
}
if self.cancel_handles.contains_key(&hash) {
debug!(
?hash,
queue_len = self.pending.len(),
concurrency_limit = self.full_verify_concurrency_limit,
"block hash already queued for inbound download: ignored block",
);
metrics::gauge!("gossip.queued.block.count").set(self.pending.len() as f64);
metrics::counter!("gossip.already.queued.dropped.block.hash.count").increment(1);
return DownloadAction::AlreadyQueued;
}
if self.pending.len() >= self.full_verify_concurrency_limit {
debug!(
?hash,
queue_len = self.pending.len(),
concurrency_limit = self.full_verify_concurrency_limit,
"too many blocks queued for inbound download: ignored block",
);
metrics::gauge!("gossip.queued.block.count").set(self.pending.len() as f64);
metrics::counter!("gossip.full.queue.dropped.block.hash.count").increment(1);
return DownloadAction::FullQueue;
}
let advertiser_ip = advertiser.map(|addr| addr.ip());
if let Some(ip) = advertiser_ip {
if self.in_flight_ips.contains(&ip) {
debug!(
?hash,
?advertiser,
"already have an in-flight inbound download from peer IP: ignored block",
);
metrics::counter!("gossip.peer.limit.dropped.block.hash.count").increment(1);
return DownloadAction::TooManyFromPeer;
}
}
let (cancel_tx, mut cancel_rx) = oneshot::channel::<()>();
let state = self.state.clone();
let read_state = self.read_state.clone();
let network = self.network.clone();
let verifier = self.verifier.clone();
let latest_chain_tip = self.latest_chain_tip.clone();
let full_verify_concurrency_limit = self.full_verify_concurrency_limit;
let fut = async move {
match state.clone().oneshot(zs::Request::KnownBlock(hash)).await {
Ok(zs::Response::KnownBlock(None)) => Ok(()),
Ok(zs::Response::KnownBlock(Some(_))) => Err("already present".into()),
Ok(_) => unreachable!("wrong response"),
Err(e) => Err(e),
}
.map_err(|e| (e, None))?;
let download_start = Instant::now();
let response = timeout(
zn::constants::REQUEST_TIMEOUT + BLOCK_DOWNLOAD_TIMEOUT,
network.oneshot(zn::Request::BlockDownload { hash, advertiser }),
)
.await
.map_err(|e| (BoxError::from(e), None))?
.map_err(|e| (e, None))?;
metrics::histogram!("gossip.block.download.duration_seconds")
.record(download_start.elapsed().as_secs_f64());
let early_relay = matches!(response, zn::Response::EarlyBlocks(_));
let (block, advertiser_addr) = if let zn::Response::Blocks(blocks)
| zn::Response::EarlyBlocks(blocks) = response
{
assert_eq!(
blocks.len(),
1,
"wrong number of blocks in response to a single hash",
);
blocks
.first()
.expect("just checked length")
.available()
.expect(
"unexpected missing block status: single block failures should be errors",
)
} else {
unreachable!("wrong response to block request");
};
metrics::counter!("gossip.downloaded.block.count").increment(1);
let tip_height = latest_chain_tip.best_tip_height();
let max_lookahead_height = if let Some(tip_height) = tip_height {
let lookahead = HeightDiff::try_from(full_verify_concurrency_limit)
.expect("fits in HeightDiff");
(tip_height + lookahead).expect("tip is much lower than Height::MAX")
} else {
let genesis_lookahead =
u32::try_from(full_verify_concurrency_limit - 1).expect("fits in u32");
block::Height(genesis_lookahead)
};
let min_accepted_height = tip_height
.map(|tip_height| {
block::Height(tip_height.0.saturating_sub(zs::MAX_BLOCK_REORG_HEIGHT))
})
.unwrap_or(block::Height(0));
let block_height = block
.coinbase_height()
.ok_or_else(|| {
debug!(
?hash,
"gossiped block with no height: dropped downloaded block"
);
metrics::counter!("gossip.no.height.dropped.block.count").increment(1);
BoxError::from("gossiped block with no height")
})
.map_err(|e| (e, None))?;
if block_height > max_lookahead_height {
debug!(
?hash,
?block_height,
?tip_height,
?max_lookahead_height,
lookahead_limit = full_verify_concurrency_limit,
"gossiped block height too far ahead of the tip: dropped downloaded block",
);
metrics::counter!("gossip.max.height.limit.dropped.block.count").increment(1);
let advertiser_addr = advertiser_if_parent_contradicts(
state,
block.header.previous_block_hash,
block_height,
advertiser_addr,
)
.await;
return Err((
BoxError::from(HeightLimitError::AboveLookahead {
height: block_height,
hash,
}),
advertiser_addr,
));
} else if block_height < min_accepted_height {
debug!(
?hash,
?block_height,
?tip_height,
?min_accepted_height,
behind_tip_limit = ?zs::MAX_BLOCK_REORG_HEIGHT,
"gossiped block height behind the finalized tip: dropped downloaded block",
);
metrics::counter!("gossip.min.height.limit.dropped.block.count").increment(1);
let advertiser_addr = advertiser_if_parent_contradicts(
state,
block.header.previous_block_hash,
block_height,
advertiser_addr,
)
.await;
return Err((
BoxError::from(HeightLimitError::BehindTip {
height: block_height,
hash,
}),
advertiser_addr,
));
}
let early_block = early_relay.then(|| block.clone());
let early_check = match (&early_block, &read_state) {
(Some(block), Some(read_state)) => {
start_early_relay_check(read_state, &latest_chain_tip, block)
}
_ => None,
};
let verify_start = Instant::now();
let result = verifier
.oneshot(zebra_consensus::Request::Commit(block))
.await
.map(|hash| (hash, block_height, verify_start.elapsed()))
.map_err(|e| (e, advertiser_addr));
match (result, early_block, read_state) {
(Err((error, Some(advertiser_addr))), Some(block), Some(read_state))
if is_later_validation_failure(&*error) =>
{
let parent = block.header.previous_block_hash;
if early_block_is_authenticated(
read_state,
latest_chain_tip,
block,
block_height,
early_check,
)
.await
{
Err((
BoxError::from(AuthenticatedBlockRejected {
error,
peer: advertiser_addr,
parent,
}),
None,
))
} else {
Err((error, Some(advertiser_addr)))
}
}
(result, _, _) => result,
}
}
.map_ok(|(hash, height, verify_commit)| {
metrics::histogram!("gossip.block.verify_commit.duration_seconds")
.record(verify_commit.as_secs_f64());
info!(?height, "downloaded and verified gossiped block");
metrics::counter!("gossip.verified.block.count").increment(1);
hash
})
.map_err(move |(e, advertiser_addr)| (e, hash, advertiser_addr))
.in_current_span();
let task = tokio::spawn(async move {
tokio::select! {
biased;
_ = &mut cancel_rx => {
trace!("task cancelled prior to completion");
metrics::counter!("gossip.cancelled.count").increment(1);
Err(("canceled".into(), hash, None))
}
verification = fut => verification,
}
});
self.pending.push(task);
assert!(
self.cancel_handles
.insert(hash, (cancel_tx, advertiser_ip))
.is_none(),
"blocks are only queued once"
);
if let Some(ip) = advertiser_ip {
assert!(
self.in_flight_ips.insert(ip),
"the per-IP cap check above rejects any IP already in flight",
);
}
debug!(
?hash,
queue_len = self.pending.len(),
concurrency_limit = self.full_verify_concurrency_limit,
"queued hash for download",
);
metrics::gauge!("gossip.queued.block.count").set(self.pending.len() as f64);
DownloadAction::AddedToQueue
}
}