Expunge error-chain (feat. tomaka) (#2662)

* Remove error_chain

* Expunge error-chain from rpc and service.

* Expunge from transaction pool.

* Expunge from node/cli

* Expunge from keystore.

* Remove some boilerplate.

* Fix remaining stuff.

* Improve on deprecation message.

* Fix issues.

* Fix trnsaction pool tests.

* Fix the rest.

* Fix borked merge.

* Update lock
This commit is contained in:
Tomasz Drwięga
2019-05-24 11:35:31 +02:00
committed by Gavin Wood
parent 69ffec5822
commit c162fc5ff1
68 changed files with 951 additions and 1158 deletions
-1
View File
@@ -24,7 +24,6 @@ runtime_primitives = { package = "sr-primitives", path = "../../sr-primitives" }
futures = "0.1.17"
tokio = "0.1.7"
parking_lot = "0.7.1"
error-chain = "0.12"
log = "0.4"
[dev-dependencies]
+10 -12
View File
@@ -50,7 +50,7 @@ use runtime_primitives::traits::{
Block, Header, Digest, DigestItemFor, DigestItem, ProvideRuntimeApi, AuthorityIdFor, Zero,
};
use primitives::Pair;
use inherents::{InherentDataProviders, InherentData, RuntimeString};
use inherents::{InherentDataProviders, InherentData};
use authorities::AuthoritiesApi;
use futures::{Future, IntoFuture, future, stream::Stream};
@@ -122,10 +122,6 @@ fn slot_author<P: Pair>(slot_num: u64, authorities: &[AuthorityId<P>]) -> Option
Some(current_author)
}
fn inherent_to_common_error(err: RuntimeString) -> consensus_common::Error {
consensus_common::ErrorKind::InherentData(err.into()).into()
}
/// A digest item which is usable with aura consensus.
pub trait CompatibleDigestItem<T: Pair>: Sized {
/// Construct a digest item which contains a slot number and a signature on the
@@ -177,7 +173,8 @@ impl SlotCompatible for AuraSlotCompatible {
) -> Result<(TimestampInherent, AuraInherent), consensus_common::Error> {
data.timestamp_inherent_data()
.and_then(|t| data.aura_inherent_data().map(|a| (t, a)))
.map_err(inherent_to_common_error)
.map_err(Into::into)
.map_err(consensus_common::Error::InherentData)
}
}
@@ -448,7 +445,7 @@ impl<B: Block, C, E, I, P, Error, SO> SlotWorker<B> for AuraWorker<C, E, I, P, S
);
}
})
.map_err(|e| consensus_common::ErrorKind::ClientImport(format!("{:?}", e)).into())
.map_err(|e| consensus_common::Error::ClientImport(format!("{:?}", e)).into())
)
}
}
@@ -738,7 +735,7 @@ fn initialize_authorities_cache<B, C>(client: &C) -> Result<(), ConsensusError>
return Ok(());
}
let map_err = |error| consensus_common::Error::from(consensus_common::ErrorKind::ClientImport(
let map_err = |error| consensus_common::Error::from(consensus_common::Error::ClientImport(
format!(
"Error initializing authorities cache: {}",
error,
@@ -766,7 +763,7 @@ fn authorities<B, C>(client: &C, at: &BlockId<B>) -> Result<Vec<AuthorityIdFor<B
} else {
CoreApi::authorities(&*client.runtime_api(), at).ok()
}
}).ok_or_else(|| consensus_common::ErrorKind::InvalidAuthoritiesSet.into())
}).ok_or_else(|| consensus_common::Error::InvalidAuthoritiesSet.into())
}
/// The Aura import queue type.
@@ -780,7 +777,8 @@ fn register_aura_inherent_data_provider(
if !inherent_data_providers.has_provider(&srml_aura::INHERENT_IDENTIFIER) {
inherent_data_providers
.register_provider(srml_aura::InherentDataProvider::new(slot_duration))
.map_err(inherent_to_common_error)
.map_err(Into::into)
.map_err(consensus_common::Error::InherentData)
} else {
Ok(())
}
@@ -1000,7 +998,7 @@ mod tests {
let header_hash: H256 = header.hash();
let to_sign = (slot_num, header_hash).encode();
let signature = pair.sign(&to_sign[..]);
let item = <generic::DigestItem<_, _, _> as CompatibleDigestItem<sr25519::Pair>>::aura_seal(
slot_num,
signature,
@@ -1120,7 +1118,7 @@ mod tests {
// Different slot is ok.
assert!(check_header::<_, B, P>(&c, 5, header3, header3_hash, &authorities, false).is_ok());
// Here we trigger pruning and save header 4.
assert!(check_header::<_, B, P>(&c, PRUNING_BOUND + 2, header4, header4_hash, &authorities, false).is_ok());
-1
View File
@@ -25,7 +25,6 @@ runtime_primitives = { package = "sr-primitives", path = "../../sr-primitives" }
futures = "0.1.26"
tokio = "0.1.18"
parking_lot = "0.7.1"
error-chain = "0.12.0"
log = "0.4.6"
schnorrkel = "0.1.1"
rand = "0.6.5"
+9 -11
View File
@@ -40,7 +40,7 @@ use primitives::{
sr25519::{Public, Signature, LocalizedSignature, self},
};
use merlin::Transcript;
use inherents::{InherentDataProviders, InherentData, RuntimeString};
use inherents::{InherentDataProviders, InherentData};
use substrate_telemetry::{telemetry, CONSENSUS_TRACE, CONSENSUS_DEBUG, CONSENSUS_WARN, CONSENSUS_INFO};
use schnorrkel::{
keys::Keypair,
@@ -191,10 +191,6 @@ impl Config {
}
}
fn inherent_to_common_error(err: RuntimeString) -> consensus_common::Error {
consensus_common::ErrorKind::InherentData(err.into()).into()
}
/// A digest item which is usable with BABE consensus.
pub trait CompatibleDigestItem: Sized {
/// Construct a digest item which contains a slot number and a signature
@@ -243,7 +239,8 @@ impl SlotCompatible for BabeSlotCompatible {
trace!(target: "babe", "extract timestamp");
data.timestamp_inherent_data()
.and_then(|t| data.babe_inherent_data().map(|a| (t, a)))
.map_err(slots::inherent_to_common_error)
.map_err(Into::into)
.map_err(consensus_common::Error::InherentData)
}
}
@@ -520,7 +517,7 @@ impl<B: Block, C, E, I, Error, SO> SlotWorker<B> for BabeWorker<C, E, I, SO> whe
})
.map_err(|e| {
warn!("Client import failed: {:?}", e);
consensus_common::ErrorKind::ClientImport(format!("{:?}", e)).into()
consensus_common::Error::ClientImport(format!("{:?}", e))
})
)
}
@@ -585,7 +582,7 @@ fn check_header<B: Block + Sized, C: AuxStore>(
format!("VRF verification failed")
})?
};
if check(&inout, threshold) {
match check_equivocation(&client, slot_now, slot_num, header.clone(), signer.clone()) {
Ok(Some(equivocation_proof)) => {
@@ -797,7 +794,7 @@ fn authorities<B, C>(client: &C, at: &BlockId<B>) -> Result<
panic!("We dont support deprecated code with new consensus algorithms, \
therefore this is unreachable; qed")
}
}).ok_or_else(|| consensus_common::ErrorKind::InvalidAuthoritiesSet.into())
}).ok_or(consensus_common::Error::InvalidAuthoritiesSet)
}
/// The BABE import queue type.
@@ -812,7 +809,8 @@ fn register_babe_inherent_data_provider(
if !inherent_data_providers.has_provider(&srml_babe::INHERENT_IDENTIFIER) {
inherent_data_providers
.register_provider(srml_babe::InherentDataProvider::new(slot_duration))
.map_err(inherent_to_common_error)
.map_err(Into::into)
.map_err(consensus_common::Error::InherentData)
} else {
Ok(())
}
@@ -1019,7 +1017,7 @@ mod tests {
Default::default(),
0,
);
let (inout, proof, _batchable_proof) = get_keypair(&pair).vrf_sign_n_check(transcript, |inout| check(inout, u64::MAX)).unwrap();
let pre_hash: H256 = header.hash();
let to_sign = (slot_num, pre_hash, proof.to_bytes()).encode();
+1 -1
View File
@@ -6,12 +6,12 @@ description = "Common utilities for substrate consensus"
edition = "2018"
[dependencies]
derive_more = "0.14.0"
crossbeam-channel = "0.3.4"
libp2p = { version = "0.8.1", default-features = false }
log = "0.4"
primitives = { package = "substrate-primitives", path= "../../primitives" }
inherents = { package = "substrate-inherents", path = "../../inherents" }
error-chain = "0.12"
futures = "0.1"
rstd = { package = "sr-std", path = "../../sr-std" }
runtime_version = { package = "sr-version", path = "../../sr-version" }
+59 -90
View File
@@ -16,100 +16,69 @@
//! Error types in Consensus
use runtime_version::RuntimeVersion;
use error_chain::{error_chain, error_chain_processing, impl_error_chain_processed,
impl_extract_backtrace, impl_error_chain_kind};
use primitives::ed25519::{Public, Signature};
use std::error;
error_chain! {
errors {
/// Missing state at block with given descriptor.
StateUnavailable(b: String) {
description("State missing at given block."),
display("State unavailable at block {}", b),
}
/// Result type alias.
pub type Result<T> = std::result::Result<T, Error>;
/// I/O terminated unexpectedly
IoTerminated {
description("I/O terminated unexpectedly."),
display("I/O terminated unexpectedly."),
}
/// Error type.
#[derive(Debug, derive_more::Display, derive_more::From)]
pub enum Error {
/// Missing state at block with given descriptor.
#[display(fmt="State unavailable at block {}", _0)]
StateUnavailable(String),
/// I/O terminated unexpectedly
#[display(fmt="I/O terminated unexpectedly.")]
IoTerminated,
/// Unable to schedule wakeup.
#[display(fmt="Timer error: {}", _0)]
FaultyTimer(tokio_timer::Error),
/// Error while working with inherent data.
#[display(fmt="InherentData error: {}", _0)]
InherentData(String),
/// Unable to propose a block.
#[display(fmt="Unable to create block proposal.")]
CannotPropose,
/// Error checking signature
#[display(fmt="Message signature {:?} by {:?} is invalid.", _0, _1)]
InvalidSignature(Signature, Public),
/// Invalid authorities set received from the runtime.
#[display(fmt="Current state of blockchain has invalid authorities set")]
InvalidAuthoritiesSet,
/// Account is not an authority.
#[display(fmt="Message sender {:?} is not a valid authority.", _0)]
InvalidAuthority(Public),
/// Authoring interface does not match the runtime.
#[display(fmt="Authoring for current \
runtime is not supported. Native ({}) cannot author for on-chain ({}).", native, on_chain)]
IncompatibleAuthoringRuntime { native: RuntimeVersion, on_chain: RuntimeVersion },
/// Authoring interface does not match the runtime.
#[display(fmt="Authoring for current runtime is not supported since it has no version.")]
RuntimeVersionMissing,
/// Authoring interface does not match the runtime.
#[display(fmt="Authoring in current build is not supported since it has no runtime.")]
NativeRuntimeMissing,
/// Justification requirements not met.
#[display(fmt="Invalid justification.")]
InvalidJustification,
/// Some other error.
#[display(fmt="Other error: {}", _0)]
Other(Box<error::Error + Send>),
/// Error from the client while importing
#[display(fmt="Import failed: {}", _0)]
ClientImport(String),
/// Error from the client while importing
#[display(fmt="Chain lookup failed: {}", _0)]
ChainLookup(String),
}
/// Unable to schedule wakeup.
FaultyTimer(e: ::tokio_timer::Error) {
description("Timer error"),
display("Timer error: {}", e),
}
/// Error while working with inherent data.
InherentData(e: String) {
description("InherentData error"),
display("InherentData error: {}", e),
}
/// Unable to propose a block.
CannotPropose {
description("Unable to create block proposal."),
display("Unable to create block proposal."),
}
/// Error checking signature
InvalidSignature(s: Signature, a: Public) {
description("Message signature is invalid"),
display("Message signature {:?} by {:?} is invalid.", s, a),
}
/// Invalid authorities set received from the runtime.
InvalidAuthoritiesSet {
description("authorities set is invalid"),
display("Current state of blockchain has invalid authorities set"),
}
/// Account is not an authority.
InvalidAuthority(a: Public) {
description("Message sender is not a valid authority"),
display("Message sender {:?} is not a valid authority.", a),
}
/// Authoring interface does not match the runtime.
IncompatibleAuthoringRuntime(native: RuntimeVersion, on_chain: RuntimeVersion) {
description("Authoring for current runtime is not supported"),
display("Authoring for current runtime is not supported. Native ({}) cannot author for on-chain ({}).", native, on_chain),
}
/// Authoring interface does not match the runtime.
RuntimeVersionMissing {
description("Current runtime has no version"),
display("Authoring for current runtime is not supported since it has no version."),
}
/// Authoring interface does not match the runtime.
NativeRuntimeMissing {
description("This build has no native runtime"),
display("Authoring in current build is not supported since it has no runtime."),
}
/// Justification requirements not met.
InvalidJustification {
description("Invalid justification"),
display("Invalid justification."),
}
/// Some other error.
Other(e: Box<::std::error::Error + Send>) {
description("Other error")
display("Other error: {}", e.description())
}
/// Error from the client while importing
ClientImport(reason: String) {
description("Import failed"),
display("Import failed: {}", reason),
}
/// Error from the client while importing
ChainLookup(reason: String) {
description("Looking up chain failed"),
display("Chain lookup failed: {}", reason),
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Error::FaultyTimer(ref err) => Some(err),
Error::Other(ref err) => Some(&**err),
_ => None,
}
}
}
@@ -20,37 +20,36 @@ use super::MAX_BLOCK_SIZE;
use parity_codec::Encode;
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, One, CheckedConversion};
use error_chain::{error_chain, error_chain_processing, impl_error_chain_processed,
impl_extract_backtrace, impl_error_chain_kind, bail};
// This is just a best effort to encode the number. None indicated that it's too big to encode
// in a u128.
type BlockNumber = Option<u128>;
error_chain! {
errors {
BadProposalFormat {
description("Proposal provided not a block."),
display("Proposal provided not a block."),
}
WrongParentHash(expected: String, got: String) {
description("Proposal had wrong parent hash."),
display("Proposal had wrong parent hash. Expected {:?}, got {:?}", expected, got),
}
WrongNumber(expected: BlockNumber, got: BlockNumber) {
description("Proposal had wrong number."),
display("Proposal had wrong number. Expected {:?}, got {:?}", expected, got),
}
ProposalTooLarge(size: usize) {
description("Proposal exceeded the maximum size."),
display(
"Proposal exceeded the maximum size of {} by {} bytes.",
MAX_BLOCK_SIZE, size.saturating_sub(MAX_BLOCK_SIZE)
),
}
}
/// Result type alias.
pub type Result<T> = std::result::Result<T, Error>;
/// Error type.
#[derive(Debug, derive_more::Display)]
pub enum Error {
/// Proposal provided not a block.
#[display(fmt="Proposal provided not a block.")]
BadProposalFormat,
/// Proposal had wrong parent hash.
#[display(fmt="Proposal had wrong parent hash. Expected {:?}, got {:?}", expected, got)]
WrongParentHash { expected: String, got: String },
/// Proposal had wrong number.
#[display(fmt="Proposal had wrong number. Expected {:?}, got {:?}", expected, got)]
WrongNumber { expected: BlockNumber, got: BlockNumber },
/// Proposal exceeded the maximum size.
#[display(
fmt="Proposal exceeded the maximum size of {} by {} bytes.",
"MAX_BLOCK_SIZE", "_0.saturating_sub(MAX_BLOCK_SIZE)"
)]
ProposalTooLarge(usize),
}
impl std::error::Error for Error {}
/// Attempt to evaluate a substrate block as a node block, returning error
/// upon any initial validity checks failing.
pub fn evaluate_initial<Block: BlockT>(
@@ -61,24 +60,24 @@ pub fn evaluate_initial<Block: BlockT>(
let encoded = Encode::encode(proposal);
let proposal = Block::decode(&mut &encoded[..])
.ok_or_else(|| ErrorKind::BadProposalFormat)?;
.ok_or_else(|| Error::BadProposalFormat)?;
if encoded.len() > MAX_BLOCK_SIZE {
bail!(ErrorKind::ProposalTooLarge(encoded.len()))
return Err(Error::ProposalTooLarge(encoded.len()))
}
if *parent_hash != *proposal.header().parent_hash() {
bail!(ErrorKind::WrongParentHash(
format!("{:?}", *parent_hash),
format!("{:?}", proposal.header().parent_hash())
));
return Err(Error::WrongParentHash {
expected: format!("{:?}", *parent_hash),
got: format!("{:?}", proposal.header().parent_hash())
});
}
if parent_number + One::one() != *proposal.header().number() {
bail!(ErrorKind::WrongNumber(
parent_number.checked_into::<u128>().map(|x| x + 1),
(*proposal.header().number()).checked_into::<u128>()
));
return Err(Error::WrongNumber {
expected: parent_number.checked_into::<u128>().map(|x| x + 1),
got: (*proposal.header().number()).checked_into::<u128>(),
});
}
Ok(())
+1 -1
View File
@@ -47,7 +47,7 @@ pub mod evaluation;
// block size limit.
const MAX_BLOCK_SIZE: usize = 4 * 1024 * 1024 + 512;
pub use self::error::{Error, ErrorKind};
pub use self::error::Error;
pub use block_import::{
BlockImport, BlockOrigin, ForkChoiceStrategy, ImportedAux, ImportBlock, ImportResult,
JustificationImport, FinalityProofImport, FinalityProofRequestBuilder,
+1 -1
View File
@@ -6,6 +6,7 @@ description = "Rhododendron Round-Based consensus-algorithm for substrate"
edition = "2018"
[dependencies]
derive_more = "0.14.0"
futures = "0.1.17"
codec = { package = "parity-codec", version = "3.2", features = ["derive"] }
primitives = { package = "substrate-primitives", path = "../../primitives" }
@@ -20,7 +21,6 @@ runtime_version = { package = "sr-version", path = "../../sr-version" }
runtime_io = { package = "sr-io", path = "../../sr-io" }
tokio = "0.1.7"
parking_lot = "0.7.1"
error-chain = "0.12"
log = "0.4"
rhododendron = { version = "0.5.0", features = ["codec"] }
exit-future = "0.1"
+24 -33
View File
@@ -15,45 +15,36 @@
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Error types in the rhododendron Consensus service.
use consensus::error::{Error as CommonError, ErrorKind as CommonErrorKind};
use consensus::error::{Error as CommonError};
use primitives::AuthorityId;
use client;
use error_chain::{error_chain, error_chain_processing, impl_error_chain_processed,
impl_extract_backtrace, impl_error_chain_kind};
error_chain! {
links {
Client(client::error::Error, client::error::ErrorKind);
Common(CommonError, CommonErrorKind);
}
errors {
NotValidator(id: AuthorityId) {
description("Local account ID not a validator at this block."),
display("Local account ID ({:?}) not a validator at this block.", id),
}
PrematureDestruction {
description("Proposer destroyed before finishing proposing or evaluating"),
display("Proposer destroyed before finishing proposing or evaluating"),
}
Timer(e: ::tokio::timer::Error) {
description("Failed to register or resolve async timer."),
display("Timer failed: {}", e),
}
Executor(e: ::futures::future::ExecuteErrorKind) {
description("Unable to dispatch agreement future"),
display("Unable to dispatch agreement future: {:?}", e),
}
}
/// A result alias.
pub type Result<T> = std::result::Result<T, Error>;
/// A RHD error type.
#[derive(Debug, derive_more::Display, derive_more::From)]
pub enum Error {
/// Client error.
Client(client::error::Error),
/// Consensus error.
Common(CommonError),
/// Local account ID not a validator at this block.
#[display(fmt="Local account ID ({:?}) not a validator at this block.", _0)]
NotValidator(AuthorityId),
/// Proposer destroyed before finishing proposing or evaluating
#[display(fmt="Proposer destroyed before finishing proposing or evaluating")]
PrematureDestruction,
/// Failed to register or resolve async timer.
#[display(fmt="Timer failed: {}", _0)]
Timer(tokio::timer::Error),
/// Unable to dispatch agreement future
#[display(fmt="Unable to dispatch agreement future: {:?}", _0)]
Executor(futures::future::ExecuteErrorKind),
}
impl From<::rhododendron::InputStreamConcluded> for Error {
fn from(_: ::rhododendron::InputStreamConcluded) -> Self {
CommonErrorKind::IoTerminated.into()
}
}
impl From<CommonErrorKind> for Error {
fn from(e: CommonErrorKind) -> Self {
CommonError::from(e).into()
CommonError::IoTerminated.into()
}
}
@@ -15,5 +15,4 @@ inherents = { package = "substrate-inherents", path = "../../inherents" }
futures = "0.1.17"
tokio = "0.1.7"
parking_lot = "0.7.1"
error-chain = "0.12"
log = "0.4"
@@ -65,11 +65,6 @@ pub trait SlotCompatible {
) -> Result<(u64, u64), consensus_common::Error>;
}
/// Convert an inherent error to common error.
pub fn inherent_to_common_error(err: inherents::RuntimeString) -> consensus_common::Error {
consensus_common::ErrorKind::InherentData(err.into()).into()
}
/// Start a new slot worker in a separate thread.
#[deprecated(since = "1.1", note = "Please spawn a thread manually")]
pub fn start_slot_worker_thread<B, C, W, SO, SC, T, OnExit>(
+3 -3
View File
@@ -19,7 +19,7 @@
//! This is used instead of `tokio_timer::Interval` because it was unreliable.
use super::SlotCompatible;
use consensus_common::{Error, ErrorKind};
use consensus_common::Error;
use futures::prelude::*;
use futures::try_ready;
use inherents::{InherentData, InherentDataProviders};
@@ -125,7 +125,7 @@ impl<SC: SlotCompatible> Stream for Slots<SC> {
if let Some(ref mut inner_delay) = self.inner_delay {
try_ready!(inner_delay
.poll()
.map_err(|e| Error::from(ErrorKind::FaultyTimer(e))));
.map_err(Error::FaultyTimer));
}
// timeout has fired.
@@ -133,7 +133,7 @@ impl<SC: SlotCompatible> Stream for Slots<SC> {
let inherent_data = self
.inherent_data_providers
.create_inherent_data()
.map_err(crate::inherent_to_common_error)?;
.map_err(|s| consensus_common::Error::InherentData(s.into_owned()))?;
let (timestamp, slot_num) = SC::extract_timestamp_and_slot(&inherent_data)?;
// reschedule delay for next slot.