Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ignore AlreadyInChain error in the syncer #2890

Merged
merged 6 commits into from
Oct 20, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions zebra-consensus/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ pub struct BlockVerifier<S, V> {

// TODO: dedupe with crate::error::BlockError
#[non_exhaustive]
#[allow(missing_docs)]
#[derive(Debug, Error)]
pub enum VerifyBlockError {
#[error("unable to verify depth for block {hash} from chain state during block verification")]
Expand Down
1 change: 1 addition & 0 deletions zebra-consensus/src/checkpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,7 @@ where
}

#[derive(Debug, Error)]
#[allow(missing_docs)]
pub enum VerifyCheckpointError {
#[error("checkpoint request after the final checkpoint has been verified")]
Finished,
Expand Down
3 changes: 3 additions & 0 deletions zebra-consensus/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,12 @@ pub mod chain;
#[allow(missing_docs)]
pub mod error;

pub use block::VerifyBlockError;
pub use checkpoint::VerifyCheckpointError;
pub use checkpoint::MAX_CHECKPOINT_BYTE_COUNT;
pub use checkpoint::MAX_CHECKPOINT_HEIGHT_GAP;
pub use config::Config;
pub use error::BlockError;

/// A boxed [`std::error::Error`].
pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
42 changes: 33 additions & 9 deletions zebrad/src/components/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,15 @@ use zebra_chain::{
block::{self, Block},
parameters::genesis_hash,
};
use zebra_consensus::{
chain::VerifyChainError, BlockError, VerifyBlockError, VerifyCheckpointError,
};
use zebra_network as zn;
use zebra_state as zs;

use crate::{config::ZebradConfig, BoxError};
use crate::{
components::sync::downloads::BlockDownloadVerifyError, config::ZebradConfig, BoxError,
};

mod downloads;
mod gossip;
Expand Down Expand Up @@ -315,10 +320,7 @@ where
tracing::trace!(?hash, "verified and committed block to state");
}
Err(e) => {
if format!("{:?}", e).contains("AlreadyVerified {") {
tracing::debug!(error = ?e, "block was already verified, possibly from a previous sync run, continuing");
} else {
tracing::warn!(?e, "error downloading and verifying block");
if Self::should_restart_sync(e) {
continue 'sync;
}
}
Expand Down Expand Up @@ -352,10 +354,7 @@ where
}

Err(e) => {
if format!("{:?}", e).contains("AlreadyVerified {") {
tracing::debug!(error = ?e, "block was already verified, possibly from a previous sync run, continuing");
} else {
tracing::warn!(?e, "error downloading and verifying block");
if Self::should_restart_sync(e) {
continue 'sync;
}
}
Expand Down Expand Up @@ -715,4 +714,29 @@ where
self.downloads.in_flight() as f64
);
}

/// Return if the sync should be restarted based on the given error
/// from the block downloader and verifier stream.
fn should_restart_sync(e: BlockDownloadVerifyError) -> bool {
match e {
BlockDownloadVerifyError::Invalid(VerifyChainError::Checkpoint(
VerifyCheckpointError::AlreadyVerified { .. },
)) => {
tracing::debug!(error = ?e, "block was already verified, possibly from a previous sync run, continuing");
false
}
BlockDownloadVerifyError::Invalid(VerifyChainError::Block(
VerifyBlockError::Block {
source: BlockError::AlreadyInChain(_, _),
},
)) => {
tracing::debug!(error = ?e, "block is already in chain, possibly from a previous sync run, continuing");
false
}
_ => {
tracing::warn!(?e, "error downloading and verifying block");
true
}
}
}
}
42 changes: 35 additions & 7 deletions zebrad/src/components/sync/downloads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use futures::{
stream::{FuturesUnordered, Stream},
};
use pin_project::pin_project;
use thiserror::Error;
use tokio::{sync::oneshot, task::JoinHandle};
use tower::{hedge, Service, ServiceExt};
use tracing_futures::Instrument;
Expand All @@ -33,6 +34,23 @@ impl<Request: Clone> hedge::Policy<Request> for AlwaysHedge {
}
}

/// Errors that can occur while downloading and verifying a block.
#[derive(Error, Debug)]
#[allow(dead_code)]
pub enum BlockDownloadVerifyError {
#[error("error downloading block")]
DownloadFailed(#[source] BoxError),

#[error("error from the verifier service")]
VerifierError(#[source] BoxError),

#[error("block did not pass consensus validation")]
Invalid(#[from] zebra_consensus::chain::VerifyChainError),

#[error("block download / verification was cancelled")]
Cancelled,
}

/// Represents a [`Stream`] of download and verification tasks during chain sync.
#[pin_project]
#[derive(Debug)]
Expand All @@ -54,7 +72,8 @@ where
// Internal downloads state
/// A list of pending block download and verify tasks.
#[pin]
pending: FuturesUnordered<JoinHandle<Result<block::Hash, (BoxError, block::Hash)>>>,
pending:
FuturesUnordered<JoinHandle<Result<block::Hash, (BlockDownloadVerifyError, block::Hash)>>>,

/// A list of channels that can be used to cancel pending block download and
/// verify tasks.
Expand All @@ -68,7 +87,7 @@ where
ZV: Service<Arc<Block>, Response = block::Hash, Error = BoxError> + Send + Clone + 'static,
ZV::Future: Send,
{
type Item = Result<block::Hash, BoxError>;
type Item = Result<block::Hash, BlockDownloadVerifyError>;

fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let this = self.project();
Expand Down Expand Up @@ -163,9 +182,9 @@ where
_ = &mut cancel_rx => {
tracing::trace!("task cancelled prior to download completion");
metrics::counter!("sync.cancelled.download.count", 1);
return Err("canceled block_fetch_verify".into())
return Err(BlockDownloadVerifyError::Cancelled)
}
rsp = block_req => rsp?,
rsp = block_req => rsp.map_err(BlockDownloadVerifyError::DownloadFailed)?,
};

let block = if let zn::Response::Blocks(blocks) = rsp {
Expand All @@ -178,22 +197,31 @@ where
};
metrics::counter!("sync.downloaded.block.count", 1);

let rsp = verifier.ready_and().await?.call(block);
let rsp = verifier
.ready_and()
.await
.map_err(BlockDownloadVerifyError::VerifierError)?
.call(block);
// TODO: if the verifier and cancel are both ready, which should
// we prefer? (Currently, select! chooses one at random.)
let verification = tokio::select! {
_ = &mut cancel_rx => {
tracing::trace!("task cancelled prior to verification");
metrics::counter!("sync.cancelled.verify.count", 1);
return Err("canceled block_fetch_verify".into())
return Err(BlockDownloadVerifyError::Cancelled)
}
verification = rsp => verification,
};
if verification.is_ok() {
metrics::counter!("sync.verified.block.count", 1);
}

verification
verification.map_err(|err| {
match err.downcast::<zebra_consensus::chain::VerifyChainError>() {
Ok(e) => BlockDownloadVerifyError::Invalid(*e),
Err(e) => BlockDownloadVerifyError::VerifierError(e),
}
})
}
.in_current_span()
// Tack the hash onto the error so we can remove the cancel handle
Expand Down