use std::{
cmp::max,
collections::{HashMap, HashSet, VecDeque},
pin::Pin,
task::Poll,
time::Duration,
};
use color_eyre::eyre::{eyre, Report};
use futures::{
future::{self, FutureExt as _},
stream::{self, FuturesUnordered, StreamExt as _, TryStreamExt as _},
};
use indexmap::IndexSet;
use serde::{Deserialize, Serialize};
use tokio::{
sync::{mpsc, watch},
task::JoinError,
time::{sleep, sleep_until, timeout, Instant},
};
use tower::{
builder::ServiceBuilder, limit::ConcurrencyLimit, retry::Retry, timeout::Timeout, Service,
ServiceExt,
};
use zebra_chain::{
block::{self, Height, HeightDiff},
chain_tip::ChainTip,
};
use zebra_consensus::{
error::TransactionError, BlockError, RouterError, VerifyBlockError, VerifyCheckpointError,
};
use zebra_network as zn;
use zebra_state as zs;
use crate::{
components::sync::downloads::BlockDownloadVerifyError, config::ZebradConfig, BoxError,
};
mod diagnostics;
mod downloads;
pub mod end_of_support;
mod gossip;
mod hedge;
pub(crate) mod progress;
mod recent_sync_lengths;
mod status;
#[cfg(test)]
mod tests;
use downloads::Downloads;
use hedge::SuccessHedge;
pub(crate) use diagnostics::{RestartReason, SyncDiagnostics};
pub use downloads::VERIFICATION_PIPELINE_SCALING_MULTIPLIER;
pub use gossip::{gossip_best_tip_block_hashes, BlockGossipError};
pub use progress::{record_tip_block_delay, show_block_chain_progress};
pub use recent_sync_lengths::RecentSyncLengths;
pub use status::SyncStatus;
fn is_not_found(error: &dyn std::error::Error) -> bool {
format!("{error:?}").contains("NotFound")
}
fn interleave_peer_hashes(
download_set: &mut IndexSet<block::Hash>,
mut responses: VecDeque<impl Iterator<Item = block::Hash>>,
) {
download_set.clear();
while let Some(mut hashes) = responses.pop_front() {
if let Some(hash) = hashes.next() {
download_set.insert(hash);
responses.push_back(hashes);
}
}
}
const FANOUT: usize = 3;
const KNOWN_BLOCK_CHECK_CONCURRENCY: usize = 16;
const BLOCK_DOWNLOAD_RETRY_LIMIT: usize = 3;
const MAX_BLOCK_REOBTAIN_RETRIES: u8 = 3;
const MIN_UTXO_RACE_DROPS_BEFORE_RESTART: usize = 4;
pub const MIN_CHECKPOINT_CONCURRENCY_LIMIT: usize = zebra_consensus::MAX_CHECKPOINT_HEIGHT_GAP;
pub const DEFAULT_CHECKPOINT_CONCURRENCY_LIMIT: usize = MAX_TIPS_RESPONSE_HASH_COUNT * 2;
pub const MIN_CONCURRENCY_LIMIT: usize = 1;
pub const MAX_TIPS_RESPONSE_HASH_COUNT: usize = 500;
pub const TIPS_RESPONSE_TIMEOUT: Duration = Duration::from_secs(6);
const EXTEND_TIP_ROUNDS: usize = 3;
#[cfg(not(test))]
pub const PEER_GOSSIP_DELAY: Duration = Duration::from_secs(7);
#[cfg(test)]
pub const PEER_GOSSIP_DELAY: Duration = Duration::from_millis(10);
pub(super) const BLOCK_DOWNLOAD_TIMEOUT: Duration = zn::constants::REQUEST_TIMEOUT;
const BLOCK_DOWNLOAD_ROUND_TIMEOUT: Duration =
BLOCK_DOWNLOAD_TIMEOUT.saturating_mul(BLOCK_DOWNLOAD_RETRY_LIMIT as u32 + 1);
pub(super) const BLOCK_VERIFY_TIMEOUT: Duration = Duration::from_secs(8 * 60);
const FINAL_CHECKPOINT_BLOCK_VERIFY_TIMEOUT: Duration = Duration::from_secs(2 * 60);
const FINAL_CHECKPOINT_BLOCK_VERIFY_TIMEOUT_LIMIT: HeightDiff = 100;
const SYNC_RESTART_DELAY: Duration = Duration::from_secs(67);
const REGTEST_SYNC_RESTART_DELAY: Duration = Duration::from_secs(2);
const GENESIS_TIMEOUT_RETRY: Duration = Duration::from_secs(10);
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields, default)]
pub struct Config {
#[serde(alias = "max_concurrent_block_requests")]
pub download_concurrency_limit: usize,
#[serde(alias = "lookahead_limit")]
pub checkpoint_verify_concurrency_limit: usize,
pub full_verify_concurrency_limit: usize,
pub parallel_cpu_threads: usize,
}
impl Default for Config {
fn default() -> Self {
Self {
download_concurrency_limit: 50,
checkpoint_verify_concurrency_limit: DEFAULT_CHECKPOINT_CONCURRENCY_LIMIT,
full_verify_concurrency_limit: 20,
parallel_cpu_threads: 0,
}
}
}
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
struct CheckedTip {
tip: block::Hash,
expected_next: block::Hash,
}
pub struct ChainSync<ZN, ZS, ZSR, ZV, ZSTip>
where
ZN: Service<zn::Request, Response = zn::Response, Error = BoxError>
+ Send
+ Sync
+ Clone
+ 'static,
ZN::Future: Send + 'static,
ZS: Service<zs::Request, Response = zs::Response, Error = BoxError>
+ Send
+ Sync
+ Clone
+ 'static,
ZS::Future: Send,
ZSR: Service<zs::ReadRequest, Response = zs::ReadResponse, Error = BoxError>
+ Send
+ Sync
+ Clone
+ 'static,
ZSR::Future: Send,
ZV: Service<zebra_consensus::Request, Response = block::Hash, Error = BoxError>
+ Send
+ Sync
+ Clone
+ 'static,
ZV::Future: Send,
ZSTip: ChainTip + Clone + Send + 'static,
{
genesis_hash: block::Hash,
max_checkpoint_height: Height,
checkpoint_verify_concurrency_limit: usize,
full_verify_concurrency_limit: usize,
is_regtest: bool,
tip_network: Timeout<ZN>,
downloads: Pin<
Box<
Downloads<
ConcurrencyLimit<SuccessHedge<ConcurrencyLimit<Retry<zn::RetryLimit, ZN>>>>,
Timeout<ZV>,
ZSR,
ZSTip,
>,
>,
>,
state: ZS,
latest_chain_tip: ZSTip,
prospective_tips: HashSet<CheckedTip>,
recent_syncs: RecentSyncLengths,
past_lookahead_limit_receiver: zs::WatchReceiver<bool>,
misbehavior_sender: mpsc::Sender<zn::MisbehaviorReport>,
reobtain_hashes: IndexSet<block::Hash>,
block_reobtain_retries: HashMap<block::Hash, u8>,
utxo_race_drops: usize,
diagnostics: watch::Sender<SyncDiagnostics>,
}
#[derive(Debug)]
struct RestartError {
reason: RestartReason,
kind: Option<&'static str>,
error: Report,
}
impl RestartError {
fn new(reason: RestartReason, error: impl Into<Report>) -> Self {
Self {
reason,
kind: None,
error: error.into(),
}
}
}
impl<ZN, ZS, ZSR, ZV, ZSTip> ChainSync<ZN, ZS, ZSR, ZV, ZSTip>
where
ZN: Service<zn::Request, Response = zn::Response, Error = BoxError>
+ Send
+ Sync
+ Clone
+ 'static,
ZN::Future: Send + 'static,
ZS: Service<zs::Request, Response = zs::Response, Error = BoxError>
+ Send
+ Sync
+ Clone
+ 'static,
ZS::Future: Send,
ZSR: Service<zs::ReadRequest, Response = zs::ReadResponse, Error = BoxError>
+ Send
+ Sync
+ Clone
+ 'static,
ZSR::Future: Send,
ZV: Service<zebra_consensus::Request, Response = block::Hash, Error = BoxError>
+ Send
+ Sync
+ Clone
+ 'static,
ZV::Future: Send,
ZSTip: ChainTip + Clone + Send + 'static,
{
#[allow(clippy::too_many_arguments)]
pub fn new(
config: &ZebradConfig,
max_checkpoint_height: Height,
peers: ZN,
verifier: ZV,
state: ZS,
read_state: ZSR,
latest_chain_tip: ZSTip,
misbehavior_sender: mpsc::Sender<zn::MisbehaviorReport>,
) -> (Self, SyncStatus) {
let mut download_concurrency_limit = config.sync.download_concurrency_limit;
let mut checkpoint_verify_concurrency_limit =
config.sync.checkpoint_verify_concurrency_limit;
let mut full_verify_concurrency_limit = config.sync.full_verify_concurrency_limit;
if download_concurrency_limit < MIN_CONCURRENCY_LIMIT {
warn!(
"configured download concurrency limit {} too low, increasing to {}",
config.sync.download_concurrency_limit, MIN_CONCURRENCY_LIMIT,
);
download_concurrency_limit = MIN_CONCURRENCY_LIMIT;
}
if checkpoint_verify_concurrency_limit < MIN_CHECKPOINT_CONCURRENCY_LIMIT {
warn!(
"configured checkpoint verify concurrency limit {} too low, increasing to {}",
config.sync.checkpoint_verify_concurrency_limit, MIN_CHECKPOINT_CONCURRENCY_LIMIT,
);
checkpoint_verify_concurrency_limit = MIN_CHECKPOINT_CONCURRENCY_LIMIT;
}
if full_verify_concurrency_limit < MIN_CONCURRENCY_LIMIT {
warn!(
"configured full verify concurrency limit {} too low, increasing to {}",
config.sync.full_verify_concurrency_limit, MIN_CONCURRENCY_LIMIT,
);
full_verify_concurrency_limit = MIN_CONCURRENCY_LIMIT;
}
let tip_network = Timeout::new(peers.clone(), TIPS_RESPONSE_TIMEOUT);
let block_network = SuccessHedge::new(
ServiceBuilder::new()
.concurrency_limit(download_concurrency_limit)
.retry(zn::RetryLimit::new(BLOCK_DOWNLOAD_RETRY_LIMIT))
.service(peers),
);
let block_network = ConcurrencyLimit::new(block_network, download_concurrency_limit);
let verifier = Timeout::new(verifier, BLOCK_VERIFY_TIMEOUT);
let (sync_status, recent_syncs) = SyncStatus::new_for_network(&config.network.network);
let (past_lookahead_limit_sender, past_lookahead_limit_receiver) = watch::channel(false);
let past_lookahead_limit_receiver = zs::WatchReceiver::new(past_lookahead_limit_receiver);
let downloads = Box::pin(Downloads::new(
block_network,
verifier,
read_state,
latest_chain_tip.clone(),
past_lookahead_limit_sender,
max(
checkpoint_verify_concurrency_limit,
full_verify_concurrency_limit,
),
max_checkpoint_height,
));
let (diagnostics, diagnostics_receiver) = watch::channel(SyncDiagnostics {
in_flight_blocks: downloads.in_flight_blocks(),
..SyncDiagnostics::default()
});
let sync_status = sync_status.with_diagnostics(diagnostics_receiver);
let new_syncer = Self {
genesis_hash: config.network.network.genesis_hash(),
max_checkpoint_height,
checkpoint_verify_concurrency_limit,
full_verify_concurrency_limit,
is_regtest: config.network.network.is_regtest(),
tip_network,
downloads,
state,
latest_chain_tip,
prospective_tips: HashSet::new(),
recent_syncs,
past_lookahead_limit_receiver,
misbehavior_sender,
reobtain_hashes: IndexSet::new(),
block_reobtain_retries: HashMap::new(),
utxo_race_drops: 0,
diagnostics,
};
(new_syncer, sync_status)
}
#[instrument(skip(self))]
pub async fn sync(mut self) -> Result<(), Report> {
self.request_genesis().await?;
loop {
let start_tip = self.latest_chain_tip.best_tip_height();
let result = self.try_to_sync().await;
if result.is_err() {
self.count_finished_block_errors();
self.downloads.cancel_all();
self.reobtain_hashes.clear();
self.block_reobtain_retries.clear();
}
self.update_metrics();
let restart_delay = if self.is_regtest {
REGTEST_SYNC_RESTART_DELAY
} else {
SYNC_RESTART_DELAY
};
let state_tip = self.latest_chain_tip.best_tip_height();
let made_progress = state_tip > start_tip;
let (reason, kind, error) = match result {
Ok(reason) => (reason, None, None),
Err(restart) => (
restart.reason,
restart.kind,
Some(format!("{:#}", restart.error)),
),
};
self.record_restart(reason, made_progress);
if error.is_some() && !made_progress {
warn!(
reason = reason.as_str(),
kind,
error,
timeout = ?restart_delay,
?state_tip,
"sync failed without advancing the state tip, waiting to restart sync"
);
} else {
info!(
reason = reason.as_str(),
kind,
made_progress,
error,
timeout = ?restart_delay,
?state_tip,
"waiting to restart sync"
);
}
sleep(restart_delay).await;
}
}
fn record_restart(&self, reason: RestartReason, made_progress: bool) {
metrics::counter!(
"sync.restart.count",
"reason" => reason.as_str(),
"made_progress" => if made_progress { "true" } else { "false" },
)
.increment(1);
self.diagnostics.send_modify(|diagnostics| {
diagnostics.last_restart = Some(reason);
diagnostics.restarts_without_progress = if made_progress {
0
} else {
diagnostics.restarts_without_progress.saturating_add(1)
};
});
}
#[instrument(skip(self))]
async fn try_to_sync(&mut self) -> Result<RestartReason, RestartError> {
self.prospective_tips = HashSet::new();
self.utxo_race_drops = 0;
self.downloads.take_cancelled_network_wait();
while let Poll::Ready(Some(response)) = futures::poll!(self.downloads.next()) {
self.handle_block_response(response)
.map_err(Self::block_restart_error)?;
}
self.block_reobtain_retries.retain(|hash, _| {
self.downloads.is_queued(hash) || self.reobtain_hashes.contains(hash)
});
info!(
state_tip = ?self.latest_chain_tip.best_tip_height(),
"starting sync, obtaining new tips"
);
let mut extra_hashes = match timeout(SYNC_RESTART_DELAY, self.obtain_tips()).await {
Ok(tips) => {
tips.map_err(|e| Self::tips_restart_error(RestartReason::ObtainTipsError, e))?
}
Err(elapsed) => {
return Err(self.stage_timeout_error(RestartReason::ObtainTipsTimeout, elapsed));
}
};
self.update_metrics();
let mut chain_tip = self.latest_chain_tip.clone();
let mut last_height = chain_tip.best_tip_height();
let mut progress_deadline = Instant::now() + BLOCK_VERIFY_TIMEOUT;
while !self.prospective_tips.is_empty()
|| !extra_hashes.is_empty()
|| !self.reobtain_hashes.is_empty()
{
let result = {
let step = self.try_to_sync_once(extra_hashes);
tokio::pin!(step);
loop {
tokio::select! {
biased;
Ok(()) = chain_tip.best_tip_changed() => {
let height = chain_tip.best_tip_height();
if height > last_height {
last_height = height;
progress_deadline = Instant::now() + BLOCK_VERIFY_TIMEOUT;
}
}
result = &mut step => break Some(result),
_ = sleep_until(progress_deadline) => break None,
}
}
};
match result {
Some(result) => extra_hashes = result?,
None => {
self.count_cancelled_network_wait();
info!("no chain progress before the sync deadline, backing off");
return Ok(RestartReason::SyncStepTimeout);
}
}
}
info!("exhausted prospective tip set");
Ok(RestartReason::ExhaustedTips)
}
#[instrument(skip(self, extra_hashes))]
async fn try_to_sync_once(
&mut self,
mut extra_hashes: IndexSet<block::Hash>,
) -> Result<IndexSet<block::Hash>, RestartError> {
while let Poll::Ready(Some(rsp)) = futures::poll!(self.downloads.next()) {
self.handle_block_response(rsp)
.map_err(Self::block_restart_error)?;
}
self.reobtain_missing_blocks().await;
self.update_metrics();
while !self.downloads.is_empty()
&& (self.downloads.in_flight() >= self.lookahead_limit()
|| (self.downloads.in_flight() >= self.lookahead_limit() / 2
&& self.past_lookahead_limit_receiver.cloned_watch_data()))
{
trace!(
tips.len = self.prospective_tips.len(),
in_flight = self.downloads.in_flight(),
extra_hashes = extra_hashes.len(),
lookahead_limit = self.lookahead_limit(),
state_tip = ?self.latest_chain_tip.best_tip_height(),
"waiting for pending blocks",
);
let response = self.downloads.next().await.expect("downloads is nonempty");
self.handle_block_response(response)
.map_err(Self::block_restart_error)?;
self.reobtain_missing_blocks().await;
self.update_metrics();
}
if !extra_hashes.is_empty() {
debug!(
tips.len = self.prospective_tips.len(),
in_flight = self.downloads.in_flight(),
extra_hashes = extra_hashes.len(),
lookahead_limit = self.lookahead_limit(),
state_tip = ?self.latest_chain_tip.best_tip_height(),
"requesting more blocks",
);
let response = self.request_blocks(extra_hashes).await;
extra_hashes =
Self::handle_hash_response(response).map_err(Self::block_restart_error)?;
} else {
info!(
tips.len = self.prospective_tips.len(),
in_flight = self.downloads.in_flight(),
extra_hashes = extra_hashes.len(),
lookahead_limit = self.lookahead_limit(),
state_tip = ?self.latest_chain_tip.best_tip_height(),
"extending tips",
);
extra_hashes = self
.extend_tips()
.await
.map_err(|e| Self::tips_restart_error(RestartReason::ExtendTipsError, e))?;
}
self.update_metrics();
Ok(extra_hashes)
}
async fn reobtain_missing_blocks(&mut self) {
if self.reobtain_hashes.is_empty() {
return;
}
while let Some(hash) = self.reobtain_hashes.first().copied() {
if let Err(error) = self.queue_block(hash).await {
trace!(?hash, ?error, "re-download of missing block not queued");
if !matches!(
error,
BlockDownloadVerifyError::DuplicateBlockQueuedForDownload { .. }
| BlockDownloadVerifyError::AlreadyRejected { .. }
) {
break;
}
}
self.reobtain_hashes.shift_remove(&hash);
}
}
#[instrument(skip(self))]
async fn obtain_tips(&mut self) -> Result<IndexSet<block::Hash>, Report> {
let stage_start = std::time::Instant::now();
let block_locator = self
.state
.ready()
.await
.map_err(|e| eyre!(e))?
.call(zebra_state::Request::BlockLocator)
.await
.map(|response| match response {
zebra_state::Response::BlockLocator(block_locator) => block_locator,
_ => unreachable!(
"GetBlockLocator request can only result in Response::BlockLocator"
),
})
.map_err(|e| eyre!(e))?;
debug!(
tip = ?block_locator.first().expect("we have at least one block locator object"),
?block_locator,
"got block locator and trying to obtain new chain tips"
);
let mut requests = FuturesUnordered::new();
for attempt in 0..FANOUT {
if attempt > 0 {
tokio::task::yield_now().await;
}
let ready_tip_network = self.tip_network.ready().await;
requests.push(tokio::spawn(ready_tip_network.map_err(|e| eyre!(e))?.call(
zn::Request::FindBlocks {
known_blocks: block_locator.clone(),
stop: None,
},
)));
}
let mut download_set = IndexSet::new();
let mut response_candidates = Vec::with_capacity(FANOUT);
let mut peer_hashes = VecDeque::new();
while let Some(res) = requests.next().await {
match res
.unwrap_or_else(|e @ JoinError { .. }| {
if e.is_panic() {
panic!("panic in obtain tips task: {e:?}");
} else {
info!(
"task error during obtain tips task: {e:?},\
is Zebra shutting down?"
);
Err(e.into())
}
})
.map_err::<Report, _>(|e| eyre!(e))
{
Ok(zn::Response::BlockHashes(hashes)) => {
trace!(?hashes);
if hashes.is_empty() {
continue;
}
let mut first_unknown = None;
for (i, &hash) in hashes.iter().enumerate() {
if !self.state_contains(hash).await? {
first_unknown = Some(i);
break;
}
}
debug!(hashes.len = ?hashes.len(), ?first_unknown);
let unknown_hashes = if let Some(index) = first_unknown {
&hashes[index..]
} else {
continue;
};
trace!(?unknown_hashes);
if let Some(end) = unknown_hashes.rchunks_exact(2).next() {
let new_tip = CheckedTip {
tip: end[0],
expected_next: end[1],
};
response_candidates.push((new_tip, unknown_hashes.to_vec()));
} else {
debug!("downloading response that extends only one block");
}
let prev_download_len = download_set.len();
download_set.extend(unknown_hashes);
let new_download_len = download_set.len();
let new_hashes = new_download_len - prev_download_len;
debug!(new_hashes, "added hashes to download set");
metrics::histogram!("sync.obtain.response.hash.count")
.record(new_hashes as f64);
let known_hashes = hashes.len() - unknown_hashes.len();
peer_hashes.push_back(hashes.into_iter().skip(known_hashes));
}
Ok(_) => unreachable!("network returned wrong response"),
Err(e) => debug!(?e),
}
}
interleave_peer_hashes(&mut download_set, peer_hashes);
let state = self.state.clone();
let download_set = stream::iter(download_set)
.map(move |hash| {
let state = state.clone();
async move {
let response = state
.oneshot(zs::Request::KnownBlock(hash))
.await
.map_err(|error| eyre!(error))?;
let zs::Response::KnownBlock(location) = response else {
unreachable!("wrong response to known block request");
};
let is_known =
location.is_some_and(|location| location != zs::KnownBlock::Queue);
Ok::<_, Report>((!is_known).then_some(hash))
}
})
.buffered(KNOWN_BLOCK_CHECK_CONCURRENCY)
.try_filter_map(future::ok)
.try_collect::<IndexSet<_>>()
.await?;
let mut eligible_response_hashes = HashSet::new();
for (response_tip, response_hashes) in response_candidates {
if !download_set.contains(&response_tip.tip)
|| !download_set.contains(&response_tip.expected_next)
{
continue;
}
if !eligible_response_hashes.contains(&response_tip.expected_next) {
self.prospective_tips
.retain(|tip| !response_hashes.contains(&tip.expected_next));
self.prospective_tips.insert(response_tip);
}
eligible_response_hashes.extend(response_hashes);
}
debug!(?self.prospective_tips);
let new_downloads = download_set.len();
debug!(new_downloads, "queueing new downloads");
metrics::gauge!("sync.obtain.queued.hash.count").set(new_downloads as f64);
self.recent_syncs.push_obtain_tips_length(new_downloads);
let response = self.request_blocks(download_set).await;
metrics::histogram!("sync.stage.duration_seconds", "stage" => "obtain_tips")
.record(stage_start.elapsed().as_secs_f64());
Self::handle_hash_response(response).map_err(Into::into)
}
#[instrument(skip(self))]
async fn extend_tips(&mut self) -> Result<IndexSet<block::Hash>, Report> {
let stage_start = std::time::Instant::now();
let tips = std::mem::take(&mut self.prospective_tips);
let mut download_set = IndexSet::new();
let mut peer_hashes = VecDeque::new();
debug!(tips = ?tips.len(), "trying to extend chain tips");
for tip in tips {
debug!(?tip, "asking peers to extend chain tip");
for round in 0..EXTEND_TIP_ROUNDS {
if round > 0 {
debug!(
?tip,
round, "no peer answered, asking other peers to extend chain tip"
);
}
let mut answered = false;
let mut responses = FuturesUnordered::new();
for attempt in 0..FANOUT {
if attempt > 0 {
tokio::task::yield_now().await;
}
let ready_tip_network = self.tip_network.ready().await;
responses.push(tokio::spawn(ready_tip_network.map_err(|e| eyre!(e))?.call(
zn::Request::FindBlocks {
known_blocks: vec![tip.tip],
stop: None,
},
)));
}
while let Some(res) = responses.next().await {
match res
.expect("panic in spawned extend tips request")
.map_err::<Report, _>(|e| eyre!(e))
{
Ok(zn::Response::BlockHashes(hashes)) => {
debug!(first = ?hashes.first(), len = ?hashes.len());
trace!(?hashes);
let unknown_hashes = match hashes.as_slice() {
[expected_hash, rest @ ..]
if expected_hash == &tip.expected_next =>
{
rest
}
[first_hash, expected_hash, rest @ ..]
if expected_hash == &tip.expected_next =>
{
debug!(?first_hash,
?tip.expected_next,
?tip.tip,
"unexpected first hash, but the second matches: using the hashes after the match");
rest
}
[] => {
answered = true;
continue;
}
[single_hash] => {
debug!(?single_hash,
?tip.expected_next,
?tip.tip,
"discarding response containing a single unexpected hash");
continue;
}
[first_hash, second_hash, rest @ ..] => {
debug!(?first_hash,
?second_hash,
rest_len = ?rest.len(),
?tip.expected_next,
?tip.tip,
"discarding response that starts with two unexpected hashes");
continue;
}
};
answered = true;
if unknown_hashes.is_empty() {
debug!(?tip.tip, "response contained no new hashes after the expected overlap");
continue;
}
trace!(?unknown_hashes);
if let Some(end) = unknown_hashes.rchunks_exact(2).next() {
let new_tip = CheckedTip {
tip: end[0],
expected_next: end[1],
};
if !download_set.contains(&new_tip.expected_next) {
debug!(
?new_tip,
"adding new prospective tip, and removing any existing tips \
in the new block hash list",
);
self.prospective_tips
.retain(|t| !unknown_hashes.contains(&t.expected_next));
self.prospective_tips.insert(new_tip);
} else {
debug!(
?new_tip,
"discarding prospective tip: already in download set"
);
}
} else {
debug!("downloading response that extends only one block");
}
let prev_download_len = download_set.len();
download_set.extend(unknown_hashes);
let new_download_len = download_set.len();
let new_hashes = new_download_len - prev_download_len;
debug!(new_hashes, "added hashes to download set");
metrics::histogram!("sync.extend.response.hash.count")
.record(new_hashes as f64);
let known_hashes = hashes.len() - unknown_hashes.len();
peer_hashes.push_back(hashes.into_iter().skip(known_hashes));
}
Ok(_) => unreachable!("network returned wrong response"),
Err(e) => debug!(?e),
}
}
if answered {
break;
}
}
}
let new_downloads = download_set.len();
debug!(new_downloads, "queueing new downloads");
metrics::gauge!("sync.extend.queued.hash.count").set(new_downloads as f64);
self.recent_syncs.push_extend_tips_length(new_downloads);
interleave_peer_hashes(&mut download_set, peer_hashes);
let response = self.request_blocks(download_set).await;
metrics::histogram!("sync.stage.duration_seconds", "stage" => "extend_tips")
.record(stage_start.elapsed().as_secs_f64());
Self::handle_hash_response(response).map_err(Into::into)
}
async fn request_genesis(&mut self) -> Result<(), Report> {
while !self.state_contains(self.genesis_hash).await? {
info!("starting genesis block download and verify");
let response = match timeout(SYNC_RESTART_DELAY, self.request_genesis_once()).await {
Ok(response) => Ok(response),
Err(_) => Err(self.genesis_timeout()),
};
match response {
Ok(Ok(Ok(response))) => self
.handle_block_response(Ok(response))
.expect("never returns Err for Ok"),
Ok(Err(fatal_error)) => Err(fatal_error)?,
Err(error) | Ok(Ok(Err(error))) => {
if Self::should_restart_sync(&error) {
warn!(
?error,
"could not download or verify genesis block, retrying"
);
} else {
info!(
?error,
"temporary error downloading or verifying genesis block, retrying"
);
}
tokio::time::sleep(GENESIS_TIMEOUT_RETRY).await;
}
}
}
Ok(())
}
async fn request_genesis_once(
&mut self,
) -> Result<Result<(Height, block::Hash), BlockDownloadVerifyError>, Report> {
let response = self.queue_block(self.genesis_hash).await;
Self::handle_response(response).map_err(|e| eyre!(e))?;
self.update_metrics();
let response = self
.downloads
.next()
.await
.expect("downloads is nonempty")
.inspect_err(|error| self.count_block_error(error));
self.update_metrics();
Ok(response)
}
async fn request_blocks(
&mut self,
mut hashes: IndexSet<block::Hash>,
) -> Result<IndexSet<block::Hash>, BlockDownloadVerifyError> {
let lookahead_limit = self.lookahead_limit();
debug!(
hashes.len = hashes.len(),
?lookahead_limit,
"requesting blocks",
);
let capacity = lookahead_limit
.saturating_sub(self.downloads.in_flight())
.saturating_sub(self.reobtain_hashes.len());
let extra_hashes = if hashes.len() > capacity {
hashes.split_off(capacity)
} else {
IndexSet::new()
};
for hash in hashes.into_iter() {
match self.queue_block(hash).await {
Ok(()) => {}
Err(BlockDownloadVerifyError::DuplicateBlockQueuedForDownload { .. }) => {
debug!("block request was already queued, continuing");
}
Err(BlockDownloadVerifyError::AlreadyRejected { .. }) => {
debug!("block already failed validation after early relay, continuing");
}
Err(error) => return Err(error),
}
}
Ok(extra_hashes)
}
fn lookahead_limit(&self) -> usize {
let max_checkpoint_height: usize = self
.max_checkpoint_height
.0
.try_into()
.expect("fits in usize");
let verified_height: usize = self
.latest_chain_tip
.best_tip_height()
.unwrap_or(Height(0))
.0
.try_into()
.expect("fits in usize");
if verified_height >= max_checkpoint_height {
self.full_verify_concurrency_limit
} else if max_checkpoint_height - verified_height
<= self.checkpoint_verify_concurrency_limit
{
let checkpoint_hashes = max_checkpoint_height - verified_height;
self.full_verify_concurrency_limit + checkpoint_hashes
} else {
self.checkpoint_verify_concurrency_limit
}
}
#[allow(unknown_lints)]
fn handle_block_response(
&mut self,
response: Result<(Height, block::Hash), BlockDownloadVerifyError>,
) -> Result<(), BlockDownloadVerifyError> {
if let Err(error) = &response {
self.count_block_error(error);
}
match response {
Ok((height, hash)) => {
trace!(?height, ?hash, "verified and committed block to state");
self.reobtain_hashes.shift_remove(&hash);
self.block_reobtain_retries.remove(&hash);
self.utxo_race_drops = 0;
return Ok(());
}
Err(
ref verify_error @ BlockDownloadVerifyError::Invalid {
ref error,
advertiser_addr: Some(advertiser_addr),
..
},
) if error.misbehavior_score() != 0 => {
let _ = self.misbehavior_sender.try_send(zn::MisbehaviorReport::new(
advertiser_addr,
error.misbehavior_score(),
verify_error.to_string(),
));
}
Err(
ref verify_error @ BlockDownloadVerifyError::InvalidHeight {
advertiser_addr: Some(advertiser_addr),
..
},
) => {
let _ = self.misbehavior_sender.try_send(zn::MisbehaviorReport::new(
advertiser_addr,
100,
verify_error.to_string(),
));
}
Err(
ref verify_error @ BlockDownloadVerifyError::BodyHeaderMismatch {
advertiser_addr: Some(advertiser_addr),
..
},
) => {
let _ = self.misbehavior_sender.try_send(zn::MisbehaviorReport::new(
advertiser_addr,
100,
verify_error.to_string(),
));
}
Err(
ref verify_error @ BlockDownloadVerifyError::BehindTipHeightLimit {
advertiser_addr: Some(advertiser_addr),
..
},
) => {
let _ = self.misbehavior_sender.try_send(zn::MisbehaviorReport::new(
advertiser_addr,
100,
format!("parent header contradicts coinbase height: {verify_error}"),
));
}
Err(_) => {}
};
let reobtain_hash = match &response {
Err(BlockDownloadVerifyError::DownloadFailed { hash, .. }) => Some(*hash),
Err(BlockDownloadVerifyError::DownloadTimedOut { hash }) => Some(*hash),
Err(BlockDownloadVerifyError::BehindTipHeightLimit { hash, .. }) => Some(*hash),
Err(BlockDownloadVerifyError::BodyHeaderMismatch { hash, .. }) => Some(*hash),
Err(e @ BlockDownloadVerifyError::Invalid { hash, .. })
if Self::is_utxo_lookup_timeout(e) =>
{
Some(*hash)
}
Err(BlockDownloadVerifyError::Invalid { error, hash, .. })
if error.is_auth_commitment_mismatch()
|| error.is_descendant_of_auth_commitment_mismatch()
|| error.is_body_header_mismatch()
|| Self::is_block_body_error(error) =>
{
Some(*hash)
}
Err(e @ BlockDownloadVerifyError::ValidationRequestError { hash, .. })
if Self::is_post_checkpoint_verify_timeout(e) =>
{
Some(*hash)
}
Err(e @ BlockDownloadVerifyError::Invalid { hash, .. }) if Self::is_queue_full(e) => {
Some(*hash)
}
_ => None,
};
if let Some(hash) = reobtain_hash {
let attempts = self.block_reobtain_retries.entry(hash).or_insert(0);
if *attempts < MAX_BLOCK_REOBTAIN_RETRIES {
*attempts += 1;
self.reobtain_hashes.insert(hash);
debug!(
?hash,
attempts = *attempts,
"re-queueing missing block for re-download"
);
} else {
debug!(?hash, "missing block exceeded re-download retries");
self.block_reobtain_retries.remove(&hash);
if response.as_ref().is_err_and(Self::is_queue_full) {
return response.map(|_| ());
}
}
}
if let Err(error) = &response {
if Self::is_utxo_lookup_timeout(error) {
self.utxo_race_drops += 1;
if self.utxo_race_drops
>= self
.full_verify_concurrency_limit
.max(MIN_UTXO_RACE_DROPS_BEFORE_RESTART)
{
warn!(
drops = self.utxo_race_drops,
"no block verified across a full wave of UTXO lookup timeouts, restarting sync"
);
return response.map(|_| ());
}
}
}
Self::handle_response(response)
}
fn is_utxo_lookup_timeout(e: &BlockDownloadVerifyError) -> bool {
matches!(
e,
BlockDownloadVerifyError::Invalid {
error: RouterError::Block { source },
..
} if matches!(
**source,
VerifyBlockError::Transaction(TransactionError::TransparentInputNotFound)
)
)
}
fn is_post_checkpoint_verify_timeout(e: &BlockDownloadVerifyError) -> bool {
matches!(
e,
BlockDownloadVerifyError::ValidationRequestError { error, .. }
if error.is::<tokio::time::error::Elapsed>()
)
}
fn is_queue_full(e: &BlockDownloadVerifyError) -> bool {
match e {
BlockDownloadVerifyError::Invalid {
error: RouterError::Checkpoint { source },
..
} => matches!(**source, VerifyCheckpointError::QueuedLimit),
BlockDownloadVerifyError::Invalid {
error: RouterError::Block { source },
..
} => matches!(
**source,
VerifyBlockError::Commit(zs::CommitBlockError::OrphanQueueFull)
),
_ => false,
}
}
fn block_error_kind(e: &BlockDownloadVerifyError) -> &'static str {
use BlockDownloadVerifyError::*;
match e {
Invalid { error, .. } if error.is_duplicate_request() => "already_verified",
Invalid { error, .. }
if error.is_auth_commitment_mismatch()
|| error.is_descendant_of_auth_commitment_mismatch() =>
{
"auth_commitment_mismatch"
}
Invalid { error, .. } if error.is_body_header_mismatch() => "body_header_mismatch",
e if Self::is_utxo_lookup_timeout(e) => "utxo_lookup_timeout",
e if Self::is_post_checkpoint_verify_timeout(e) => "final_checkpoint_verify_timeout",
e if Self::is_queue_full(e) => "queue_full",
Invalid { .. } => "invalid",
ValidationRequestError { error, .. }
if error.is::<tower::timeout::error::Elapsed>() =>
{
"verify_timeout"
}
ValidationRequestError { .. } => "validation_request",
DownloadFailed { error, .. } if is_not_found(error.as_ref()) => "not_found",
DownloadFailed { .. } => "download_failed",
DownloadTimedOut { .. } => "download_timed_out",
AboveLookaheadHeightLimit { .. } => "above_lookahead_limit",
BehindTipHeightLimit { .. } => "behind_tip",
InvalidHeight { .. } => "invalid_height",
BodyHeaderMismatch { .. } => "body_header_mismatch",
DuplicateBlockQueuedForDownload { .. } => "duplicate_queued",
AlreadyRejected { .. } => "already_rejected",
CancelledDuringDownload { .. }
| CancelledAwaitingVerifierReadiness { .. }
| CancelledDuringVerification { .. } => "cancelled",
NetworkServiceError { .. } => "network_service",
VerifierServiceError { .. } => "verifier_service",
Timeout => "network_ready_timeout",
GenesisTimeout => "genesis_timeout",
}
}
async fn queue_block(&mut self, hash: block::Hash) -> Result<(), BlockDownloadVerifyError> {
self.update_metrics();
let result = self.downloads.download_and_verify(hash).await;
match &result {
Ok(())
| Err(BlockDownloadVerifyError::DuplicateBlockQueuedForDownload { .. })
| Err(BlockDownloadVerifyError::AlreadyRejected { .. }) => {}
Err(error) => self.count_block_error(error),
}
result
}
fn count_cancelled_network_wait(&mut self) -> bool {
let cancelled = self.downloads.take_cancelled_network_wait();
if cancelled {
self.count_block_error(&BlockDownloadVerifyError::Timeout);
}
cancelled
}
fn stage_timeout_error(
&mut self,
reason: RestartReason,
elapsed: tokio::time::error::Elapsed,
) -> RestartError {
if self.count_cancelled_network_wait() {
Self::block_restart_error(BlockDownloadVerifyError::Timeout)
} else {
RestartError::new(reason, elapsed)
}
}
fn genesis_timeout(&mut self) -> BlockDownloadVerifyError {
if self.count_cancelled_network_wait() {
BlockDownloadVerifyError::Timeout
} else {
BlockDownloadVerifyError::GenesisTimeout
}
}
fn count_finished_block_errors(&mut self) {
while let Some(Some(response)) = self.downloads.next().now_or_never() {
if let Err(error) = response {
self.count_block_error(&error);
}
}
}
fn count_block_error(&self, error: &BlockDownloadVerifyError) {
metrics::counter!("sync.block.error.count", "kind" => Self::block_error_kind(error))
.increment(1);
}
fn tips_restart_error(reason: RestartReason, error: Report) -> RestartError {
match error.downcast::<BlockDownloadVerifyError>() {
Ok(error) => Self::block_restart_error(error),
Err(error) => RestartError::new(reason, error),
}
}
fn block_restart_error(error: BlockDownloadVerifyError) -> RestartError {
RestartError {
reason: RestartReason::BlockError,
kind: Some(Self::block_error_kind(&error)),
error: error.into(),
}
}
#[allow(unknown_lints)]
fn handle_hash_response(
response: Result<IndexSet<block::Hash>, BlockDownloadVerifyError>,
) -> Result<IndexSet<block::Hash>, BlockDownloadVerifyError> {
match response {
Ok(extra_hashes) => Ok(extra_hashes),
Err(_) => Self::handle_response(response).map(|()| IndexSet::new()),
}
}
#[allow(unknown_lints)]
fn handle_response<T>(
response: Result<T, BlockDownloadVerifyError>,
) -> Result<(), BlockDownloadVerifyError> {
match response {
Ok(_t) => Ok(()),
Err(error) => {
if Self::should_restart_sync(&error) {
Err(error)
} else {
Ok(())
}
}
}
}
pub(crate) async fn state_contains(&mut self, hash: block::Hash) -> Result<bool, Report> {
match self
.state
.ready()
.await
.map_err(|e| eyre!(e))?
.call(zebra_state::Request::KnownBlock(hash))
.await
.map_err(|e| eyre!(e))?
{
zs::Response::KnownBlock(loc) => {
Ok(loc.is_some_and(|loc| loc != zs::KnownBlock::Queue))
}
_ => unreachable!("wrong response to known block request"),
}
}
fn update_metrics(&mut self) {
let in_flight = self.downloads.in_flight();
metrics::gauge!("sync.prospective_tips.len",).set(self.prospective_tips.len() as f64);
metrics::gauge!("sync.downloads.in_flight",).set(in_flight as f64);
self.diagnostics.send_modify(|diagnostics| {
diagnostics.in_flight = in_flight;
});
}
fn is_block_validation_error(error: &RouterError) -> bool {
let invalid_commit = |error: &zs::CommitBlockError| {
let zs::CommitBlockError::ValidateContextError(error) = error else {
return false;
};
let mut error = error.as_ref();
while let zs::ValidateContextError::AncestorRejected { source, .. } = error {
error = source.as_ref();
}
!matches!(
error,
zs::ValidateContextError::NotReadyToBeCommitted { .. }
| zs::ValidateContextError::NoteCommitmentTreeError(_)
| zs::ValidateContextError::HistoryTreeError(_)
)
};
let error = match error {
RouterError::Block { source } => source.as_ref(),
RouterError::Checkpoint { source } => match source.as_ref() {
VerifyCheckpointError::VerifyBlock(error) => error,
VerifyCheckpointError::CoinbaseHeight { .. }
| VerifyCheckpointError::UnexpectedSideChain { .. }
| VerifyCheckpointError::QueuedLimit
| VerifyCheckpointError::Finished => return true,
VerifyCheckpointError::CommitCheckpointVerified(error) => {
return error
.downcast_ref::<zs::CommitCheckpointVerifiedError>()
.is_some_and(|error| invalid_commit(error.inner()));
}
_ => return false,
},
};
match error {
VerifyBlockError::Block {
source: BlockError::Other(_),
} => false,
VerifyBlockError::Block {
source: BlockError::Transaction(error),
}
| VerifyBlockError::Transaction(error) => !matches!(
error,
TransactionError::InternalDowncastError(_)
| TransactionError::CoinbaseConstruction(_)
| TransactionError::ValidateMempoolLockTimeError(_)
| TransactionError::ValidateContextError(_)
),
VerifyBlockError::Block { .. }
| VerifyBlockError::Equihash { .. }
| VerifyBlockError::Time(_)
| VerifyBlockError::Subsidy(_) => true,
VerifyBlockError::Commit(error) => invalid_commit(error),
_ => false,
}
}
fn is_block_body_error(error: &RouterError) -> bool {
if !Self::is_block_validation_error(error) {
return false;
}
let error = match error {
RouterError::Block { source } => source.as_ref(),
RouterError::Checkpoint { source } => match source.as_ref() {
VerifyCheckpointError::VerifyBlock(error) => error,
VerifyCheckpointError::CoinbaseHeight { .. } => return true,
_ => return false,
},
};
match error {
VerifyBlockError::Block { source } => !matches!(
source,
BlockError::AlreadyInChain(..)
| BlockError::InvalidDifficulty(..)
| BlockError::TargetDifficultyLimit(..)
| BlockError::DifficultyFilter(..)
),
VerifyBlockError::Transaction(_) | VerifyBlockError::Subsidy(_) => true,
_ => false,
}
}
fn should_restart_sync(e: &BlockDownloadVerifyError) -> bool {
match e {
BlockDownloadVerifyError::Invalid { error, .. } if error.is_duplicate_request() => {
debug!(error = ?e, "block was already verified or committed, possibly from a previous sync run, continuing");
false
}
BlockDownloadVerifyError::Invalid { error, .. }
if error.is_auth_commitment_mismatch() =>
{
debug!(
error = ?e,
"served block body did not match the authorizing data commitment in its \
header: the block hash is still valid and is re-requested, and the serving \
peer is scored, continuing"
);
false
}
BlockDownloadVerifyError::Invalid { error, .. }
if error.is_descendant_of_auth_commitment_mismatch() =>
{
debug!(
error = ?e,
"an ancestor's served body did not match the authorizing data commitment in \
its header: this block hash is still valid and is re-requested, continuing"
);
false
}
BlockDownloadVerifyError::Invalid { error, .. } if error.is_body_header_mismatch() => {
debug!(
error = ?e,
"served block body did not match its header: the block hash is still valid \
and is re-requested, and the serving peer is scored, continuing"
);
false
}
e if Self::is_utxo_lookup_timeout(e) => {
debug!(error = ?e, "block spends an output that is not in our state yet, re-requesting, continuing");
false
}
e if Self::is_queue_full(e) => {
debug!(error = ?e, "block verifier queue was full, re-requesting, continuing");
false
}
BlockDownloadVerifyError::CancelledDuringDownload { .. }
| BlockDownloadVerifyError::CancelledDuringVerification { .. } => {
debug!(error = ?e, "block verification was cancelled, continuing");
false
}
BlockDownloadVerifyError::BehindTipHeightLimit { .. } => {
debug!(
error = ?e,
"block height is behind the current state tip: re-requesting the hash, \
and scoring the peer if the body contradicts the parent we hold, continuing"
);
false
}
BlockDownloadVerifyError::AboveLookaheadHeightLimit { .. } => {
debug!(
error = ?e,
"block height is above the lookahead limit, \
dropping the block and continuing sync"
);
false
}
BlockDownloadVerifyError::InvalidHeight { .. } => {
debug!(
error = ?e,
"block has no valid height, \
dropping the block and continuing sync"
);
false
}
BlockDownloadVerifyError::BodyHeaderMismatch { .. } => {
debug!(
error = ?e,
"served block body did not match its header: the block hash is still valid \
and is re-requested, and the serving peer is scored, continuing"
);
false
}
BlockDownloadVerifyError::DuplicateBlockQueuedForDownload { .. } => {
debug!(
error = ?e,
"queued duplicate block hash for download, \
assuming the syncer will eventually resolve duplicates, continuing"
);
false
}
BlockDownloadVerifyError::AlreadyRejected { .. } => {
debug!(
error = ?e,
"block already failed validation after early relay, \
not downloading it again, continuing"
);
false
}
BlockDownloadVerifyError::DownloadFailed { ref error, .. }
if is_not_found(error.as_ref()) =>
{
debug!(error = ?e, "block was not found, possibly from a peer that doesn't have the block yet, continuing");
false
}
BlockDownloadVerifyError::DownloadTimedOut { .. } => {
debug!(error = ?e, "no peer delivered the block within the download round, re-requesting, continuing");
false
}
e if Self::is_post_checkpoint_verify_timeout(e) => {
debug!(error = ?e, "initial fully verified block timed out waiting for its parent's outputs, re-requesting, continuing");
false
}
BlockDownloadVerifyError::Invalid { error, .. }
if Self::is_block_validation_error(error) =>
{
debug!(error = ?e, "block validation failed, continuing sync");
false
}
BlockDownloadVerifyError::DownloadFailed { .. } => {
debug!(error = ?e, "dropping failed block and continuing sync");
false
}
_ => {
let err_str = format!("{e:?}");
if err_str.contains("NotFound") {
error!(?e,
"a BlockDownloadVerifyError that should have been filtered out was detected, \
which possibly indicates a programming error in the downcast inside \
zebrad::components::sync::downloads::Downloads::download_and_verify"
)
}
warn!(
?e,
kind = Self::block_error_kind(e),
"error downloading and verifying block"
);
true
}
}
}
}