error rework, for polkadot convenience (#7446)

Co-authored-by: Bernhard Schuster <bernhard@parity.io>
Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
This commit is contained in:
Bernhard Schuster
2020-10-28 15:04:56 +01:00
committed by GitHub
parent 1679919830
commit 9687759774
17 changed files with 152 additions and 128 deletions
+5 -3
View File
@@ -8086,7 +8086,6 @@ dependencies = [
name = "sp-blockchain" name = "sp-blockchain"
version = "2.0.0" version = "2.0.0"
dependencies = [ dependencies = [
"derive_more",
"log", "log",
"lru 0.4.3", "lru 0.4.3",
"parity-scale-codec", "parity-scale-codec",
@@ -8096,6 +8095,7 @@ dependencies = [
"sp-database", "sp-database",
"sp-runtime", "sp-runtime",
"sp-state-machine", "sp-state-machine",
"thiserror",
] ]
[[package]] [[package]]
@@ -8110,7 +8110,6 @@ dependencies = [
name = "sp-consensus" name = "sp-consensus"
version = "0.8.0" version = "0.8.0"
dependencies = [ dependencies = [
"derive_more",
"futures 0.3.5", "futures 0.3.5",
"futures-timer 3.0.2", "futures-timer 3.0.2",
"libp2p", "libp2p",
@@ -8129,6 +8128,7 @@ dependencies = [
"sp-utils", "sp-utils",
"sp-version", "sp-version",
"substrate-prometheus-endpoint", "substrate-prometheus-endpoint",
"thiserror",
"wasm-timer", "wasm-timer",
] ]
@@ -8235,6 +8235,7 @@ dependencies = [
"sp-std", "sp-std",
"sp-storage", "sp-storage",
"substrate-bip39", "substrate-bip39",
"thiserror",
"tiny-bip39", "tiny-bip39",
"tiny-keccak", "tiny-keccak",
"twox-hash", "twox-hash",
@@ -8289,11 +8290,11 @@ dependencies = [
name = "sp-inherents" name = "sp-inherents"
version = "2.0.0" version = "2.0.0"
dependencies = [ dependencies = [
"derive_more",
"parity-scale-codec", "parity-scale-codec",
"parking_lot 0.10.2", "parking_lot 0.10.2",
"sp-core", "sp-core",
"sp-std", "sp-std",
"thiserror",
] ]
[[package]] [[package]]
@@ -8564,6 +8565,7 @@ dependencies = [
"sp-runtime", "sp-runtime",
"sp-std", "sp-std",
"sp-trie", "sp-trie",
"thiserror",
"trie-db", "trie-db",
"trie-root", "trie-root",
] ]
+1 -2
View File
@@ -114,8 +114,7 @@ pub trait CallExecutor<B: BlockT> {
) -> Result<(Vec<u8>, StorageProof), sp_blockchain::Error> { ) -> Result<(Vec<u8>, StorageProof), sp_blockchain::Error> {
let trie_state = state.as_trie_backend() let trie_state = state.as_trie_backend()
.ok_or_else(|| .ok_or_else(||
Box::new(sp_state_machine::ExecutionError::UnableToGenerateProof) sp_blockchain::Error::from_state(Box::new(sp_state_machine::ExecutionError::UnableToGenerateProof) as Box<_>)
as Box<dyn sp_state_machine::Error>
)?; )?;
self.prove_at_trie_state(trie_state, overlay, method, call_data) self.prove_at_trie_state(trie_state, overlay, method, call_data)
} }
+3 -3
View File
@@ -122,7 +122,7 @@ pub fn build_proof<Header, Hasher, BlocksI, HashesI>(
prove_read_on_trie_backend( prove_read_on_trie_backend(
trie_storage, trie_storage,
blocks.into_iter().map(|number| encode_cht_key(number)), blocks.into_iter().map(|number| encode_cht_key(number)),
).map_err(ClientError::Execution) ).map_err(ClientError::from_state)
} }
/// Check CHT-based header proof. /// Check CHT-based header proof.
@@ -150,7 +150,7 @@ pub fn check_proof<Header, Hasher>(
.map(|mut map| map .map(|mut map| map
.remove(local_cht_key) .remove(local_cht_key)
.expect("checked proof of local_cht_key; qed")) .expect("checked proof of local_cht_key; qed"))
.map_err(|e| ClientError::from(e)), .map_err(ClientError::from_state),
) )
} }
@@ -174,7 +174,7 @@ pub fn check_proof_on_proving_backend<Header, Hasher>(
read_proof_check_on_proving_backend::<Hasher>( read_proof_check_on_proving_backend::<Hasher>(
proving_backend, proving_backend,
local_cht_key, local_cht_key,
).map_err(|e| ClientError::from(e)), ).map_err(ClientError::from_state),
) )
} }
+2 -2
View File
@@ -14,10 +14,10 @@ readme = "README.md"
targets = ["x86_64-unknown-linux-gnu"] targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
log = "0.4.8" log = "0.4.11"
lru = "0.4.0" lru = "0.4.0"
parking_lot = "0.10.0" parking_lot = "0.10.0"
derive_more = "0.99.2" thiserror = "1.0.21"
codec = { package = "parity-scale-codec", version = "1.3.1", default-features = false, features = ["derive"] } codec = { package = "parity-scale-codec", version = "1.3.1", default-features = false, features = ["derive"] }
sp-consensus = { version = "0.8.0", path = "../consensus/common" } sp-consensus = { version = "0.8.0", path = "../consensus/common" }
sp-runtime = { version = "2.0.0", path = "../runtime" } sp-runtime = { version = "2.0.0", path = "../runtime" }
+57 -57
View File
@@ -17,142 +17,142 @@
//! Substrate client possible errors. //! Substrate client possible errors.
use std::{self, error, result}; use std::{self, result};
use sp_state_machine; use sp_state_machine;
use sp_runtime::transaction_validity::TransactionValidityError; use sp_runtime::transaction_validity::TransactionValidityError;
use sp_consensus; use sp_consensus;
use derive_more::{Display, From};
use codec::Error as CodecError; use codec::Error as CodecError;
/// Client Result type alias /// Client Result type alias
pub type Result<T> = result::Result<T, Error>; pub type Result<T> = result::Result<T, Error>;
/// Error when the runtime failed to apply an extrinsic. /// Error when the runtime failed to apply an extrinsic.
#[derive(Debug, Display)] #[derive(Debug, thiserror::Error)]
pub enum ApplyExtrinsicFailed { pub enum ApplyExtrinsicFailed {
/// The transaction cannot be included into the current block. /// The transaction cannot be included into the current block.
/// ///
/// This doesn't necessary mean that the transaction itself is invalid, but it might be just /// This doesn't necessary mean that the transaction itself is invalid, but it might be just
/// unappliable onto the current block. /// unappliable onto the current block.
#[display(fmt = "Extrinsic is not valid: {:?}", _0)] #[error("Extrinsic is not valid: {0:?}")]
Validity(TransactionValidityError), Validity(#[from] TransactionValidityError),
/// This is used for miscellaneous errors that can be represented by string and not handleable. /// This is used for miscellaneous errors that can be represented by string and not handleable.
/// ///
/// This will become obsolete with complete migration to v4 APIs. /// This will become obsolete with complete migration to v4 APIs.
#[display(fmt = "Extrinsic failed: {:?}", _0)] #[error("Extrinsic failed: {0}")]
Msg(String), Msg(String),
} }
/// Substrate Client error /// Substrate Client error
#[derive(Debug, Display, From)] #[derive(Debug, thiserror::Error)]
pub enum Error { pub enum Error {
/// Consensus Error /// Consensus Error
#[display(fmt = "Consensus: {}", _0)] #[error(transparent)]
Consensus(sp_consensus::Error), Consensus(#[from] sp_consensus::Error),
/// Backend error. /// Backend error.
#[display(fmt = "Backend error: {}", _0)] #[error("Backend error: {0}")]
#[from(ignore)]
Backend(String), Backend(String),
/// Unknown block. /// Unknown block.
#[display(fmt = "UnknownBlock: {}", _0)] #[error("UnknownBlock: {0}")]
#[from(ignore)]
UnknownBlock(String), UnknownBlock(String),
/// The `apply_extrinsic` is not valid due to the given `TransactionValidityError`. /// The `apply_extrinsic` is not valid due to the given `TransactionValidityError`.
#[display(fmt = "{:?}", _0)] #[error(transparent)]
ApplyExtrinsicFailed(ApplyExtrinsicFailed), ApplyExtrinsicFailed(#[from] ApplyExtrinsicFailed),
/// Execution error. /// Execution error.
#[display(fmt = "Execution: {}", _0)] #[error("Execution failed: {0:?}")]
Execution(Box<dyn sp_state_machine::Error>), Execution(Box<dyn sp_state_machine::Error>),
/// Blockchain error. /// Blockchain error.
#[display(fmt = "Blockchain: {}", _0)] #[error("Blockchain")]
Blockchain(Box<Error>), Blockchain(#[source] Box<Error>),
/// Invalid authorities set received from the runtime. /// Invalid authorities set received from the runtime.
#[display(fmt = "Current state of blockchain has invalid authorities set")] #[error("Current state of blockchain has invalid authorities set")]
InvalidAuthoritiesSet, InvalidAuthoritiesSet,
/// Could not get runtime version. /// Could not get runtime version.
#[display(fmt = "Failed to get runtime version: {}", _0)] #[error("Failed to get runtime version: {0}")]
#[from(ignore)]
VersionInvalid(String), VersionInvalid(String),
/// Genesis config is invalid. /// Genesis config is invalid.
#[display(fmt = "Genesis config provided is invalid")] #[error("Genesis config provided is invalid")]
GenesisInvalid, GenesisInvalid,
/// Error decoding header justification. /// Error decoding header justification.
#[display(fmt = "error decoding justification for header")] #[error("error decoding justification for header")]
JustificationDecode, JustificationDecode,
/// Justification for header is correctly encoded, but invalid. /// Justification for header is correctly encoded, but invalid.
#[display(fmt = "bad justification for header: {}", _0)] #[error("bad justification for header: {0}")]
#[from(ignore)]
BadJustification(String), BadJustification(String),
/// Not available on light client. /// Not available on light client.
#[display(fmt = "This method is not currently available when running in light client mode")] #[error("This method is not currently available when running in light client mode")]
NotAvailableOnLightClient, NotAvailableOnLightClient,
/// Invalid remote CHT-based proof. /// Invalid remote CHT-based proof.
#[display(fmt = "Remote node has responded with invalid header proof")] #[error("Remote node has responded with invalid header proof")]
InvalidCHTProof, InvalidCHTProof,
/// Remote fetch has been cancelled. /// Remote fetch has been cancelled.
#[display(fmt = "Remote data fetch has been cancelled")] #[error("Remote data fetch has been cancelled")]
RemoteFetchCancelled, RemoteFetchCancelled,
/// Remote fetch has been failed. /// Remote fetch has been failed.
#[display(fmt = "Remote data fetch has been failed")] #[error("Remote data fetch has been failed")]
RemoteFetchFailed, RemoteFetchFailed,
/// Error decoding call result. /// Error decoding call result.
#[display(fmt = "Error decoding call result of {}: {}", _0, _1)] #[error("Error decoding call result of {0}")]
CallResultDecode(&'static str, CodecError), CallResultDecode(&'static str, #[source] CodecError),
/// Error converting a parameter between runtime and node. /// Error converting a parameter between runtime and node.
#[display(fmt = "Error converting `{}` between runtime and node", _0)] #[error("Error converting `{0}` between runtime and node")]
#[from(ignore)]
RuntimeParamConversion(String), RuntimeParamConversion(String),
/// Changes tries are not supported. /// Changes tries are not supported.
#[display(fmt = "Changes tries are not supported by the runtime")] #[error("Changes tries are not supported by the runtime")]
ChangesTriesNotSupported, ChangesTriesNotSupported,
/// Error reading changes tries configuration. /// Error reading changes tries configuration.
#[display(fmt = "Error reading changes tries configuration")] #[error("Error reading changes tries configuration")]
ErrorReadingChangesTriesConfig, ErrorReadingChangesTriesConfig,
/// Key changes query has failed. /// Key changes query has failed.
#[display(fmt = "Failed to check changes proof: {}", _0)] #[error("Failed to check changes proof: {0}")]
#[from(ignore)]
ChangesTrieAccessFailed(String), ChangesTrieAccessFailed(String),
/// Last finalized block not parent of current. /// Last finalized block not parent of current.
#[display(fmt = "Did not finalize blocks in sequential order.")] #[error("Did not finalize blocks in sequential order.")]
#[from(ignore)]
NonSequentialFinalization(String), NonSequentialFinalization(String),
/// Safety violation: new best block not descendent of last finalized. /// Safety violation: new best block not descendent of last finalized.
#[display(fmt = "Potential long-range attack: block not in finalized chain.")] #[error("Potential long-range attack: block not in finalized chain.")]
NotInFinalizedChain, NotInFinalizedChain,
/// Hash that is required for building CHT is missing. /// Hash that is required for building CHT is missing.
#[display(fmt = "Failed to get hash of block for building CHT")] #[error("Failed to get hash of block for building CHT")]
MissingHashRequiredForCHT, MissingHashRequiredForCHT,
/// Invalid calculated state root on block import. /// Invalid calculated state root on block import.
#[display(fmt = "Calculated state root does not match.")] #[error("Calculated state root does not match.")]
InvalidStateRoot, InvalidStateRoot,
/// Incomplete block import pipeline. /// Incomplete block import pipeline.
#[display(fmt = "Incomplete block import pipeline.")] #[error("Incomplete block import pipeline.")]
IncompletePipeline, IncompletePipeline,
#[display(fmt = "Transaction pool not ready for block production.")] #[error("Transaction pool not ready for block production.")]
TransactionPoolNotReady, TransactionPoolNotReady,
#[display(fmt = "Database: {}", _0)] #[error("Database")]
DatabaseError(sp_database::error::DatabaseError), DatabaseError(#[from] sp_database::error::DatabaseError),
/// A convenience variant for String /// A convenience variant for String
#[display(fmt = "{}", _0)] #[error("{0}")]
Msg(String), Msg(String),
} }
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Error::Consensus(e) => Some(e),
Error::Blockchain(e) => Some(e),
_ => None,
}
}
}
impl<'a> From<&'a str> for Error { impl<'a> From<&'a str> for Error {
fn from(s: &'a str) -> Self { fn from(s: &'a str) -> Self {
Error::Msg(s.into()) Error::Msg(s.into())
} }
} }
impl From<String> for Error {
fn from(s: String) -> Self {
Error::Msg(s)
}
}
impl From<Box<dyn sp_state_machine::Error + Send + Sync>> for Error {
fn from(e: Box<dyn sp_state_machine::Error + Send + Sync>) -> Self {
Self::from_state(e)
}
}
impl From<Box<dyn sp_state_machine::Error>> for Error {
fn from(e: Box<dyn sp_state_machine::Error>) -> Self {
Self::from_state(e)
}
}
impl Error { impl Error {
/// Chain a blockchain error. /// Chain a blockchain error.
pub fn from_blockchain(e: Box<Error>) -> Self { pub fn from_blockchain(e: Box<Error>) -> Self {
@@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
derive_more = "0.99.2" thiserror = "1.0.21"
libp2p = { version = "0.28.1", default-features = false } libp2p = { version = "0.28.1", default-features = false }
log = "0.4.8" log = "0.4.8"
sp-core = { path= "../../core", version = "2.0.0"} sp-core = { path= "../../core", version = "2.0.0"}
@@ -24,73 +24,73 @@ use std::error;
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
/// Error type. /// Error type.
#[derive(Debug, derive_more::Display, derive_more::From)] #[derive(Debug, thiserror::Error)]
pub enum Error { pub enum Error {
/// Missing state at block with given descriptor. /// Missing state at block with given descriptor.
#[display(fmt="State unavailable at block {}", _0)] #[error("State unavailable at block {0}")]
StateUnavailable(String), StateUnavailable(String),
/// I/O terminated unexpectedly /// I/O terminated unexpectedly
#[display(fmt="I/O terminated unexpectedly.")] #[error("I/O terminated unexpectedly.")]
IoTerminated, IoTerminated,
/// Intermediate missing. /// Intermediate missing.
#[display(fmt="Missing intermediate.")] #[error("Missing intermediate.")]
NoIntermediate, NoIntermediate,
/// Intermediate is of wrong type. /// Intermediate is of wrong type.
#[display(fmt="Invalid intermediate.")] #[error("Invalid intermediate.")]
InvalidIntermediate, InvalidIntermediate,
/// Unable to schedule wake-up. /// Unable to schedule wake-up.
#[display(fmt="Timer error: {}", _0)] #[error("Timer error: {0}")]
FaultyTimer(std::io::Error), FaultyTimer(#[from] std::io::Error),
/// Error while working with inherent data. /// Error while working with inherent data.
#[display(fmt="InherentData error: {}", _0)] #[error("InherentData error: {0}")]
InherentData(sp_inherents::Error), InherentData(#[from] sp_inherents::Error),
/// Unable to propose a block. /// Unable to propose a block.
#[display(fmt="Unable to create block proposal.")] #[error("Unable to create block proposal.")]
CannotPropose, CannotPropose,
/// Error checking signature /// Error checking signature
#[display(fmt="Message signature {:?} by {:?} is invalid.", _0, _1)] #[error("Message signature {0:?} by {1:?} is invalid.")]
InvalidSignature(Vec<u8>, Vec<u8>), InvalidSignature(Vec<u8>, Vec<u8>),
/// Invalid authorities set received from the runtime. /// Invalid authorities set received from the runtime.
#[display(fmt="Current state of blockchain has invalid authorities set")] #[error("Current state of blockchain has invalid authorities set")]
InvalidAuthoritiesSet, InvalidAuthoritiesSet,
/// Account is not an authority. /// Account is not an authority.
#[display(fmt="Message sender {:?} is not a valid authority.", _0)] #[error("Message sender {0:?} is not a valid authority")]
InvalidAuthority(Public), InvalidAuthority(Public),
/// Authoring interface does not match the runtime. /// Authoring interface does not match the runtime.
#[display(fmt="Authoring for current \ #[error("Authoring for current \
runtime is not supported. Native ({}) cannot author for on-chain ({}).", native, on_chain)] runtime is not supported. Native ({native}) cannot author for on-chain ({on_chain}).")]
IncompatibleAuthoringRuntime { native: RuntimeVersion, on_chain: RuntimeVersion }, IncompatibleAuthoringRuntime { native: RuntimeVersion, on_chain: RuntimeVersion },
/// Authoring interface does not match the runtime. /// Authoring interface does not match the runtime.
#[display(fmt="Authoring for current runtime is not supported since it has no version.")] #[error("Authoring for current runtime is not supported since it has no version.")]
RuntimeVersionMissing, RuntimeVersionMissing,
/// Authoring interface does not match the runtime. /// Authoring interface does not match the runtime.
#[display(fmt="Authoring in current build is not supported since it has no runtime.")] #[error("Authoring in current build is not supported since it has no runtime.")]
NativeRuntimeMissing, NativeRuntimeMissing,
/// Justification requirements not met. /// Justification requirements not met.
#[display(fmt="Invalid justification.")] #[error("Invalid justification.")]
InvalidJustification, InvalidJustification,
/// Some other error. /// Some other error.
#[display(fmt="Other error: {}", _0)] #[error(transparent)]
Other(Box<dyn error::Error + Send>), Other(#[from] Box<dyn error::Error + Sync + Send + 'static>),
/// Error from the client while importing /// Error from the client while importing
#[display(fmt="Import failed: {}", _0)] #[error("Import failed: {0}")]
#[from(ignore)]
ClientImport(String), ClientImport(String),
/// Error from the client while importing /// Error from the client while importing
#[display(fmt="Chain lookup failed: {}", _0)] #[error("Chain lookup failed: {0}")]
#[from(ignore)]
ChainLookup(String), ChainLookup(String),
/// Signing failed /// Signing failed
#[display(fmt="Failed to sign using key: {:?}. Reason: {}", _0, _1)] #[error("Failed to sign using key: {0:?}. Reason: {1}")]
CannotSign(Vec<u8>, String) CannotSign(Vec<u8>, String)
} }
impl error::Error for Error { impl core::convert::From<Public> for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> { fn from(p: Public) -> Self {
match self { Self::InvalidAuthority(p)
Error::FaultyTimer(ref err) => Some(err), }
Error::Other(ref err) => Some(&**err), }
_ => None,
} impl core::convert::From<String> for Error {
fn from(s: String) -> Self {
Self::StateUnavailable(s)
} }
} }
@@ -30,27 +30,25 @@ type BlockNumber = Option<u128>;
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
/// Error type. /// Error type.
#[derive(Debug, derive_more::Display)] #[derive(Debug, thiserror::Error)]
pub enum Error { pub enum Error {
/// Proposal provided not a block. /// Proposal provided not a block.
#[display(fmt="Proposal provided not a block: decoding error: {}", _0)] #[error("Proposal provided not a block: decoding error: {0}")]
BadProposalFormat(codec::Error), BadProposalFormat(#[from] codec::Error),
/// Proposal had wrong parent hash. /// Proposal had wrong parent hash.
#[display(fmt="Proposal had wrong parent hash. Expected {:?}, got {:?}", expected, got)] #[error("Proposal had wrong parent hash. Expected {expected:?}, got {got:?}")]
WrongParentHash { expected: String, got: String }, WrongParentHash { expected: String, got: String },
/// Proposal had wrong number. /// Proposal had wrong number.
#[display(fmt="Proposal had wrong number. Expected {:?}, got {:?}", expected, got)] #[error("Proposal had wrong number. Expected {expected:?}, got {got:?}")]
WrongNumber { expected: BlockNumber, got: BlockNumber }, WrongNumber { expected: BlockNumber, got: BlockNumber },
/// Proposal exceeded the maximum size. /// Proposal exceeded the maximum size.
#[display( #[error(
fmt="Proposal exceeded the maximum size of {} by {} bytes.", "Proposal exceeded the maximum size of {} by {} bytes.",
"MAX_BLOCK_SIZE", "_0.saturating_sub(MAX_BLOCK_SIZE)" MAX_BLOCK_SIZE, .0.saturating_sub(MAX_BLOCK_SIZE)
)] )]
ProposalTooLarge(usize), ProposalTooLarge(usize),
} }
impl std::error::Error for Error {}
/// Attempt to evaluate a substrate block as a node block, returning error /// Attempt to evaluate a substrate block as a node block, returning error
/// upon any initial validity checks failing. /// upon any initial validity checks failing.
pub fn evaluate_initial<Block: BlockT>( pub fn evaluate_initial<Block: BlockT>(
+3 -1
View File
@@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
sp-std = { version = "2.0.0", default-features = false, path = "../std" } sp-std = { version = "2.0.0", default-features = false, path = "../std" }
codec = { package = "parity-scale-codec", version = "1.3.1", default-features = false, features = ["derive"] } codec = { package = "parity-scale-codec", version = "1.3.1", default-features = false, features = ["derive"] }
log = { version = "0.4.8", default-features = false } log = { version = "0.4.11", default-features = false }
serde = { version = "1.0.101", optional = true, features = ["derive"] } serde = { version = "1.0.101", optional = true, features = ["derive"] }
byteorder = { version = "1.3.2", default-features = false } byteorder = { version = "1.3.2", default-features = false }
primitive-types = { version = "0.7.0", default-features = false, features = ["codec"] } primitive-types = { version = "0.7.0", default-features = false, features = ["codec"] }
@@ -39,6 +39,7 @@ sp-storage = { version = "2.0.0", default-features = false, path = "../storage"
parity-util-mem = { version = "0.7.0", default-features = false, features = ["primitive-types"] } parity-util-mem = { version = "0.7.0", default-features = false, features = ["primitive-types"] }
futures = { version = "0.3.1", optional = true } futures = { version = "0.3.1", optional = true }
dyn-clonable = { version = "0.9.0", optional = true } dyn-clonable = { version = "0.9.0", optional = true }
thiserror = { version = "1.0.21", optional = true }
# full crypto # full crypto
ed25519-dalek = { version = "1.0.0-pre.4", default-features = false, features = ["u64_backend", "alloc"], optional = true } ed25519-dalek = { version = "1.0.0-pre.4", default-features = false, features = ["u64_backend", "alloc"], optional = true }
@@ -74,6 +75,7 @@ default = ["std"]
std = [ std = [
"full_crypto", "full_crypto",
"log/std", "log/std",
"thiserror",
"wasmi", "wasmi",
"lazy_static", "lazy_static",
"parking_lot", "parking_lot",
+5 -1
View File
@@ -335,15 +335,19 @@ pub struct LocalizedSignature {
/// An error type for SS58 decoding. /// An error type for SS58 decoding.
#[cfg(feature = "std")] #[cfg(feature = "std")]
#[derive(Clone, Copy, Eq, PartialEq, Debug)] #[derive(Clone, Copy, Eq, PartialEq, Debug, thiserror::Error)]
pub enum PublicError { pub enum PublicError {
/// Bad alphabet. /// Bad alphabet.
#[error("Base 58 requirement is violated")]
BadBase58, BadBase58,
/// Bad length. /// Bad length.
#[error("Length is bad")]
BadLength, BadLength,
/// Unknown version. /// Unknown version.
#[error("Unknown version")]
UnknownVersion, UnknownVersion,
/// Invalid checksum. /// Invalid checksum.
#[error("Invalid checksum")]
InvalidChecksum, InvalidChecksum,
} }
+1 -1
View File
@@ -28,7 +28,7 @@ pub use sp_externalities::{Externalities, ExternalitiesExt};
/// Code execution engine. /// Code execution engine.
pub trait CodeExecutor: Sized + Send + Sync + CallInWasm + Clone + 'static { pub trait CodeExecutor: Sized + Send + Sync + CallInWasm + Clone + 'static {
/// Externalities error type. /// Externalities error type.
type Error: Display + Debug + Send + 'static; type Error: Display + Debug + Send + Sync + 'static;
/// Call a given method in the runtime. Returns a tuple of the result (either the output data /// Call a given method in the runtime. Returns a tuple of the result (either the output data
/// or an execution error) together with a `bool`, which is true if native execution was used. /// or an execution error) together with a `bool`, which is true if native execution was used.
+1 -1
View File
@@ -17,7 +17,7 @@
/// The error type for database operations. /// The error type for database operations.
#[derive(Debug)] #[derive(Debug)]
pub struct DatabaseError(pub Box<dyn std::error::Error + Send>); pub struct DatabaseError(pub Box<dyn std::error::Error + Send + Sync + 'static>);
impl std::fmt::Display for DatabaseError { impl std::fmt::Display for DatabaseError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+2 -2
View File
@@ -19,7 +19,7 @@ parking_lot = { version = "0.10.0", optional = true }
sp-std = { version = "2.0.0", default-features = false, path = "../std" } sp-std = { version = "2.0.0", default-features = false, path = "../std" }
sp-core = { version = "2.0.0", default-features = false, path = "../core" } sp-core = { version = "2.0.0", default-features = false, path = "../core" }
codec = { package = "parity-scale-codec", version = "1.3.1", default-features = false, features = ["derive"] } codec = { package = "parity-scale-codec", version = "1.3.1", default-features = false, features = ["derive"] }
derive_more = { version = "0.99.2", optional = true } thiserror = { version = "1.0.21", optional = true }
[features] [features]
default = [ "std" ] default = [ "std" ]
@@ -28,5 +28,5 @@ std = [
"sp-std/std", "sp-std/std",
"codec/std", "codec/std",
"sp-core/std", "sp-core/std",
"derive_more", "thiserror",
] ]
+2 -1
View File
@@ -46,7 +46,8 @@ use std::{sync::Arc, format};
/// An error that can occur within the inherent data system. /// An error that can occur within the inherent data system.
#[cfg(feature = "std")] #[cfg(feature = "std")]
#[derive(Debug, Encode, Decode, derive_more::Display)] #[derive(Debug, Encode, Decode, thiserror::Error)]
#[error("Inherents: {0}")]
pub struct Error(String); pub struct Error(String);
#[cfg(feature = "std")] #[cfg(feature = "std")]
@@ -184,6 +184,21 @@ impl From<UnknownTransaction> for TransactionValidityError {
} }
} }
#[cfg(feature = "std")]
impl std::error::Error for TransactionValidityError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
#[cfg(feature = "std")]
impl std::fmt::Display for TransactionValidityError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s: &'static str = (*self).into();
write!(f, "{}", s)
}
}
/// Information on a transaction's validity and, if valid, on how it relates to other transactions. /// Information on a transaction's validity and, if valid, on how it relates to other transactions.
pub type TransactionValidity = Result<ValidTransaction, TransactionValidityError>; pub type TransactionValidity = Result<ValidTransaction, TransactionValidityError>;
@@ -14,7 +14,8 @@ readme = "README.md"
targets = ["x86_64-unknown-linux-gnu"] targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
log = { version = "0.4.8", optional = true } log = { version = "0.4.11", optional = true }
thiserror = { version = "1.0.21", optional = true }
parking_lot = { version = "0.10.0", optional = true } parking_lot = { version = "0.10.0", optional = true }
hash-db = { version = "0.15.2", default-features = false } hash-db = { version = "0.15.2", default-features = false }
trie-db = { version = "0.22.0", default-features = false } trie-db = { version = "0.22.0", default-features = false }
@@ -40,14 +41,15 @@ std = [
"codec/std", "codec/std",
"hash-db/std", "hash-db/std",
"num-traits/std", "num-traits/std",
"sp-core/std", "sp-core/std",
"sp-externalities/std", "sp-externalities/std",
"sp-std/std", "sp-std/std",
"sp-trie/std", "sp-trie/std",
"trie-db/std", "trie-db/std",
"trie-root/std", "trie-root/std",
"log", "log",
"thiserror",
"parking_lot", "parking_lot",
"rand", "rand",
"sp-panic-handler", "sp-panic-handler",
] ]
@@ -22,9 +22,9 @@ use sp_std::fmt;
/// State Machine Error bound. /// State Machine Error bound.
/// ///
/// This should reflect Wasm error type bound for future compatibility. /// This should reflect Wasm error type bound for future compatibility.
pub trait Error: 'static + fmt::Debug + fmt::Display + Send {} pub trait Error: 'static + fmt::Debug + fmt::Display + Send + Sync {}
impl<T: 'static + fmt::Debug + fmt::Display + Send> Error for T {} impl<T: 'static + fmt::Debug + fmt::Display + Send + Sync> Error for T {}
/// Externalities Error. /// Externalities Error.
/// ///
@@ -32,17 +32,18 @@ impl<T: 'static + fmt::Debug + fmt::Display + Send> Error for T {}
/// would not be executed unless externalities were available. This is included for completeness, /// would not be executed unless externalities were available. This is included for completeness,
/// and as a transition away from the pre-existing framework. /// and as a transition away from the pre-existing framework.
#[derive(Debug, Eq, PartialEq)] #[derive(Debug, Eq, PartialEq)]
#[cfg_attr(feature = "std", derive(thiserror::Error))]
pub enum ExecutionError { pub enum ExecutionError {
/// Backend error. /// Backend error.
#[cfg_attr(feature = "std", error("Backend error {0:?}"))]
Backend(crate::DefaultError), Backend(crate::DefaultError),
/// The entry `:code` doesn't exist in storage so there's no way we can execute anything. /// The entry `:code` doesn't exist in storage so there's no way we can execute anything.
#[cfg_attr(feature = "std", error("`:code` entry does not exist in storage"))]
CodeEntryDoesNotExist, CodeEntryDoesNotExist,
/// Backend is incompatible with execution proof generation process. /// Backend is incompatible with execution proof generation process.
#[cfg_attr(feature = "std", error("Unable to generate proof"))]
UnableToGenerateProof, UnableToGenerateProof,
/// Invalid execution proof. /// Invalid execution proof.
#[cfg_attr(feature = "std", error("Invalid execution proof"))]
InvalidProof, InvalidProof,
} }
impl fmt::Display for ExecutionError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Externalities Error") }
}