Replace error-chain for client error (#2231)

* WIP: convert client error

* Remove error_chain for client error

* Ignore tx-pool error deprecation warning

* Update Cargo.lock files

* Fix tests

* Increment impl_version

* Derive From impls, remove allow(missing_docs)

* Remove space

* Remove redundant into()s

* Blockchain Error source

* Bump impl version
This commit is contained in:
Andrew Jones
2019-04-11 20:33:43 +01:00
committed by Bastian Köcher
parent 1e0c1d8850
commit 7f59cdb900
39 changed files with 298 additions and 290 deletions
@@ -51,11 +51,11 @@ where
/// build upon.
pub fn at_block(block_id: &BlockId<Block>, api: &'a A) -> error::Result<Self> {
let number = api.block_number_from_id(block_id)?
.ok_or_else(|| error::ErrorKind::UnknownBlock(format!("{}", block_id)))?
.ok_or_else(|| error::Error::UnknownBlock(format!("{}", block_id)))?
+ One::one();
let parent_hash = api.block_hash_from_id(block_id)?
.ok_or_else(|| error::ErrorKind::UnknownBlock(format!("{}", block_id)))?;
.ok_or_else(|| error::Error::UnknownBlock(format!("{}", block_id)))?;
let header = <<Block as BlockT>::Header as HeaderT>::new(
number,
Default::default(),
@@ -89,7 +89,7 @@ where
Ok(())
}
Err(e) => {
Err(error::ErrorKind::ApplyExtrinsicFailed(e).into())
Err(error::Error::ApplyExtrinsicFailed(e))
}
}
})
+5 -5
View File
@@ -23,7 +23,7 @@ use runtime_primitives::generic::BlockId;
use runtime_primitives::Justification;
use consensus::well_known_cache_keys;
use crate::error::{ErrorKind, Result};
use crate::error::{Error, Result};
/// Blockchain database header backend. Does not perform any validation.
pub trait HeaderBackend<Block: BlockT>: Send + Sync {
@@ -56,19 +56,19 @@ pub trait HeaderBackend<Block: BlockT>: Send + Sync {
/// Get block header. Returns `UnknownBlock` error if block is not found.
fn expect_header(&self, id: BlockId<Block>) -> Result<Block::Header> {
self.header(id)?.ok_or_else(|| ErrorKind::UnknownBlock(format!("{}", id)).into())
self.header(id)?.ok_or_else(|| Error::UnknownBlock(format!("{}", id)))
}
/// Convert an arbitrary block ID into a block number. Returns `UnknownBlock` error if block is not found.
fn expect_block_number_from_id(&self, id: &BlockId<Block>) -> Result<NumberFor<Block>> {
self.block_number_from_id(id)
.and_then(|n| n.ok_or_else(|| ErrorKind::UnknownBlock(format!("{}", id)).into()))
.and_then(|n| n.ok_or_else(|| Error::UnknownBlock(format!("{}", id))))
}
/// Convert an arbitrary block ID into a block hash. Returns `UnknownBlock` error if block is not found.
fn expect_block_hash_from_id(&self, id: &BlockId<Block>) -> Result<Block::Hash> {
self.block_hash_from_id(id)
.and_then(|n| n.ok_or_else(|| ErrorKind::UnknownBlock(format!("{}", id)).into()))
.and_then(|n| n.ok_or_else(|| Error::UnknownBlock(format!("{}", id))))
}
}
@@ -196,7 +196,7 @@ pub fn tree_route<Block: BlockT, Backend: HeaderBackend<Block>>(
let load_header = |id: BlockId<Block>| {
match backend.header(id) {
Ok(Some(hdr)) => Ok(hdr),
Ok(None) => Err(ErrorKind::UnknownBlock(format!("Unknown block {:?}", id)).into()),
Ok(None) => Err(Error::UnknownBlock(format!("Unknown block {:?}", id))),
Err(e) => Err(e),
}
};
+1 -1
View File
@@ -274,7 +274,7 @@ where
let mut overlay = OverlayedChanges::default();
let state = self.backend.state_at(*id)?;
let mut ext = Ext::new(&mut overlay, &state, self.backend.changes_trie_storage(), NeverOffchainExt::new());
self.executor.runtime_version(&mut ext).ok_or(error::ErrorKind::VersionInvalid.into())
self.executor.runtime_version(&mut ext).ok_or(error::Error::VersionInvalid.into())
}
fn call_at_state<
+3 -3
View File
@@ -32,7 +32,7 @@ pub fn read_children<
let raw_val_opt = match db.get(column, &buf[..]) {
Ok(raw_val_opt) => raw_val_opt,
Err(_) => return Err(error::ErrorKind::Backend("Error reading value from database".into()).into()),
Err(_) => return Err(error::Error::Backend("Error reading value from database".into())),
};
let raw_val = match raw_val_opt {
@@ -42,7 +42,7 @@ pub fn read_children<
let children: Vec<V> = match Decode::decode(&mut &raw_val[..]) {
Some(children) => children,
None => return Err(error::ErrorKind::Backend("Error decoding children".into()).into()),
None => return Err(error::Error::Backend("Error decoding children".into())),
};
Ok(children)
@@ -118,4 +118,4 @@ mod tests {
assert_eq!(r1, vec![1_3, 1_5]);
assert_eq!(r2.len(), 0);
}
}
}
+7 -7
View File
@@ -35,7 +35,7 @@ use state_machine::backend::InMemory as InMemoryState;
use state_machine::{MemoryDB, TrieBackend, Backend as StateBackend,
prove_read_on_trie_backend, read_proof_check, read_proof_check_on_proving_backend};
use crate::error::{Error as ClientError, ErrorKind as ClientErrorKind, Result as ClientResult};
use crate::error::{Error as ClientError, Result as ClientResult};
/// The size of each CHT. This value is passed to every CHT-related function from
/// production code. Other values are passed from tests.
@@ -160,11 +160,11 @@ fn do_check_proof<Header, Hasher, F>(
let root: Hasher::Out = convert_hash(&local_root);
let local_cht_key = encode_cht_key(local_number);
let local_cht_value = checker(root, &local_cht_key)?;
let local_cht_value = local_cht_value.ok_or_else(|| ClientErrorKind::InvalidCHTProof)?;
let local_hash = decode_cht_value(&local_cht_value).ok_or_else(|| ClientErrorKind::InvalidCHTProof)?;
let local_cht_value = local_cht_value.ok_or_else(|| ClientError::InvalidCHTProof)?;
let local_hash = decode_cht_value(&local_cht_value).ok_or_else(|| ClientError::InvalidCHTProof)?;
match &local_hash[..] == remote_hash.as_ref() {
true => Ok(()),
false => Err(ClientErrorKind::InvalidCHTProof.into()),
false => Err(ClientError::InvalidCHTProof.into()),
}
}
@@ -186,7 +186,7 @@ pub fn for_each_cht_group<Header, I, F, P>(
for block in blocks {
let new_cht_num = match block_to_cht_number(cht_size, block.as_()) {
Some(new_cht_num) => new_cht_num,
None => return Err(ClientErrorKind::Backend(format!(
None => return Err(ClientError::Backend(format!(
"Cannot compute CHT root for the block #{}", block)).into()
),
};
@@ -234,7 +234,7 @@ fn build_pairs<Header, I>(
let mut hash_number = start_num;
for hash in hashes.into_iter().take(cht_size as usize) {
let hash = hash?.ok_or_else(|| ClientError::from(
ClientErrorKind::MissingHashRequiredForCHT(cht_num.as_(), hash_number.as_())
ClientError::MissingHashRequiredForCHT(cht_num.as_(), hash_number.as_())
))?;
pairs.push((
encode_cht_key(hash_number).to_vec(),
@@ -246,7 +246,7 @@ fn build_pairs<Header, I>(
if pairs.len() as u64 == cht_size {
Ok(pairs)
} else {
Err(ClientErrorKind::MissingHashRequiredForCHT(cht_num.as_(), hash_number.as_()).into())
Err(ClientError::MissingHashRequiredForCHT(cht_num.as_(), hash_number.as_()))
}
}
+8 -9
View File
@@ -57,7 +57,7 @@ use executor::{RuntimeVersion, RuntimeInfo};
use crate::notifications::{StorageNotifications, StorageEventStream};
use crate::light::{call_executor::prove_execution, fetcher::ChangesProof};
use crate::cht;
use crate::error::{self, ErrorKind};
use crate::error;
use crate::in_mem;
use crate::block_builder::{self, api::BlockBuilder as BlockBuilderAPI};
use crate::genesis;
@@ -65,7 +65,6 @@ use consensus;
use substrate_telemetry::{telemetry, SUBSTRATE_INFO};
use log::{info, trace, warn};
use error_chain::bail;
/// Type that implements `futures::Stream` of block import events.
pub type ImportNotifications<Block> = mpsc::UnboundedReceiver<BlockImportNotification<Block>>;
@@ -383,7 +382,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
/// Reads given header and generates CHT-based header proof for CHT of given size.
pub fn header_proof_with_cht_size(&self, id: &BlockId<Block>, cht_size: u64) -> error::Result<(Block::Header, Vec<Vec<u8>>)> {
let proof_error = || error::ErrorKind::Backend(format!("Failed to generate header proof for {:?}", id));
let proof_error = || error::Error::Backend(format!("Failed to generate header proof for {:?}", id));
let header = self.backend.blockchain().expect_header(*id)?;
let block_num = *header.number();
let cht_num = cht::block_to_cht_number(cht_size, block_num).ok_or_else(proof_error)?;
@@ -409,7 +408,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
let first = first.as_();
let last_num = self.backend.blockchain().expect_block_number_from_id(&last)?.as_();
if first > last_num {
return Err(error::ErrorKind::ChangesTrieAccessFailed("Invalid changes trie range".into()).into());
return Err(error::Error::ChangesTrieAccessFailed("Invalid changes trie range".into()));
}
let finalized_number = self.backend.blockchain().info()?.finalized_number;
let oldest = storage.oldest_changes_trie_block(&config, finalized_number.as_());
@@ -440,7 +439,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
self.backend.blockchain().info()?.best_number.as_(),
&key.0)
.and_then(|r| r.map(|r| r.map(|(block, tx)| (As::sa(block), tx))).collect::<Result<_, _>>())
.map_err(|err| error::ErrorKind::ChangesTrieAccessFailed(err).into())
.map_err(|err| error::Error::ChangesTrieAccessFailed(err))
}
/// Get proof for computation of (block, extrinsic) pairs where key has been changed at given blocks range.
@@ -532,7 +531,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
max_number.as_(),
&key.0
)
.map_err(|err| error::Error::from(error::ErrorKind::ChangesTrieAccessFailed(err)))?;
.map_err(|err| error::Error::from(error::Error::ChangesTrieAccessFailed(err)))?;
// now gather proofs for all changes tries roots that were touched during key_changes_proof
// execution AND are unknown (i.e. replaced with CHT) to the requester
@@ -586,7 +585,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
let storage = self.backend.changes_trie_storage();
match (config, storage) {
(Some(config), Some(storage)) => Ok((config, storage)),
_ => Err(error::ErrorKind::ChangesTriesNotSupported.into()),
_ => Err(error::Error::ChangesTriesNotSupported.into()),
}
}
@@ -910,7 +909,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
warn!("Safety violation: attempted to revert finalized block {:?} which is not in the \
same chain as last finalized {:?}", retracted, last_finalized);
bail!(error::ErrorKind::NotInFinalizedChain);
return Err(error::Error::NotInFinalizedChain);
}
let route_from_best = crate::blockchain::tree_route(
@@ -1241,7 +1240,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
let load_header = |id: Block::Hash| -> error::Result<Block::Header> {
match self.backend.blockchain().header(BlockId::Hash(id))? {
Some(hdr) => Ok(hdr),
None => Err(ErrorKind::UnknownBlock(format!("Unknown block {:?}", id)).into()),
None => Err(Error::UnknownBlock(format!("Unknown block {:?}", id))),
}
};
+89 -131
View File
@@ -16,159 +16,117 @@
//! Substrate client possible errors.
// Silence: `use of deprecated item 'std::error::Error::cause': replaced by Error::source, which can support downcasting`
// https://github.com/paritytech/substrate/issues/1547
#![allow(deprecated)]
#![allow(missing_docs)]
use std;
use std::{self, error, result};
use state_machine;
use runtime_primitives::ApplyError;
use consensus;
use error_chain::*;
use derive_more::{Display, From};
error_chain! {
links {
Consensus(consensus::Error, consensus::ErrorKind);
}
errors {
/// Backend error.
Backend(s: String) {
description("Unrecoverable backend error"),
display("Backend error: {}", s),
}
/// Client Result type alias
pub type Result<T> = result::Result<T, Error>;
/// Unknown block.
UnknownBlock(h: String) {
description("unknown block"),
display("UnknownBlock: {}", &*h),
}
/// Substrate Client error
#[derive(Debug, Display, From)]
pub enum Error {
/// Consensus Error
#[display(fmt = "Consensus: {}", _0)]
Consensus(consensus::Error),
/// Backend error.
#[display(fmt = "Backend error: {}", _0)]
Backend(String),
/// Unknown block.
#[display(fmt = "UnknownBlock: {}", _0)]
UnknownBlock(String),
/// Applying extrinsic error.
#[display(fmt = "Extrinsic error: {:?}", _0)]
ApplyExtrinsicFailed(ApplyError),
/// Execution error.
#[display(fmt = "Execution: {}", _0)]
Execution(Box<state_machine::Error>),
/// Blockchain error.
#[display(fmt = "Blockchain: {}", _0)]
Blockchain(Box<Error>),
/// Invalid authorities set received from the runtime.
#[display(fmt = "Current state of blockchain has invalid authorities set")]
InvalidAuthoritiesSet,
/// Could not get runtime version.
#[display(fmt = "On-chain runtime does not specify version")]
VersionInvalid,
/// Genesis config is invalid.
#[display(fmt = "Genesis config provided is invalid")]
GenesisInvalid,
/// Bad justification for header.
#[display(fmt = "bad justification for header: {}", _0)]
BadJustification(String),
/// Not available on light client.
#[display(fmt = "This method is not currently available when running in light client mode")]
NotAvailableOnLightClient,
/// Invalid remote CHT-based proof.
#[display(fmt = "Remote node has responded with invalid header proof")]
InvalidCHTProof,
/// Remote fetch has been cancelled.
#[display(fmt = "Remote data fetch has been cancelled")]
RemoteFetchCancelled,
/// Remote fetch has been failed.
#[display(fmt = "Remote data fetch has been failed")]
RemoteFetchFailed,
/// Error decoding call result.
#[display(fmt = "Error decoding call result of {}", _0)]
CallResultDecode(&'static str),
/// Error converting a parameter between runtime and node.
#[display(fmt = "Error converting `{}` between runtime and node", _0)]
RuntimeParamConversion(&'static str),
/// Changes tries are not supported.
#[display(fmt = "Changes tries are not supported by the runtime")]
ChangesTriesNotSupported,
/// Key changes query has failed.
#[display(fmt = "Failed to check changes proof: {}", _0)]
ChangesTrieAccessFailed(String),
/// Last finalized block not parent of current.
#[display(fmt = "Did not finalize blocks in sequential order.")]
NonSequentialFinalization(String),
/// Safety violation: new best block not descendent of last finalized.
#[display(fmt = "Potential long-range attack: block not in finalized chain.")]
NotInFinalizedChain,
/// Hash that is required for building CHT is missing.
#[display(fmt = "Failed to get hash of block#{} for building CHT#{}", _0, _1)]
MissingHashRequiredForCHT(u64, u64),
/// A convenience variant for String
#[display(fmt = "{}", _0)]
Msg(String),
}
/// Applying extrinsic error.
ApplyExtrinsicFailed(e: ApplyError) {
description("Extrinsic error"),
display("Extrinsic error: {:?}", e),
}
/// Execution error.
Execution(e: Box<state_machine::Error>) {
description("execution error"),
display("Execution: {}", e),
}
/// Blockchain error.
Blockchain(e: Box<std::error::Error + Send>) {
description("Blockchain error"),
display("Blockchain: {}", e),
}
/// Could not get runtime version.
VersionInvalid {
description("Runtime version error"),
display("On-chain runtime does not specify version"),
}
/// Genesis config is invalid.
GenesisInvalid {
description("Genesis config error"),
display("Genesis config provided is invalid"),
}
/// Bad justification for header.
BadJustification(h: String) {
description("bad justification for header"),
display("bad justification for header: {}", &*h),
}
/// Not available on light client.
NotAvailableOnLightClient {
description("not available on light client"),
display("This method is not currently available when running in light client mode"),
}
/// Invalid remote CHT-based proof.
InvalidCHTProof {
description("invalid header proof"),
display("Remote node has responded with invalid header proof"),
}
/// Remote fetch has been cancelled.
RemoteFetchCancelled {
description("remote fetch cancelled"),
display("Remote data fetch has been cancelled"),
}
/// Remote fetch has been failed.
RemoteFetchFailed {
description("remote fetch failed"),
display("Remote data fetch has been failed"),
}
/// Error decoding call result.
CallResultDecode(method: &'static str) {
description("Error decoding call result")
display("Error decoding call result of {}", method)
}
/// Error converting a parameter between runtime and node.
RuntimeParamConversion(param: &'static str) {
description("Error converting parameter between runtime and node")
display("Error converting `{}` between runtime and node", param)
}
/// Changes tries are not supported.
ChangesTriesNotSupported {
description("changes tries are not supported"),
display("Changes tries are not supported by the runtime"),
}
/// Key changes query has failed.
ChangesTrieAccessFailed(e: String) {
description("invalid changes proof"),
display("Failed to check changes proof: {}", e),
}
/// Last finalized block not parent of current.
NonSequentialFinalization(s: String) {
description("Did not finalize blocks in sequential order."),
display("Did not finalize blocks in sequential order."),
}
/// Safety violation: new best block not descendent of last finalized.
NotInFinalizedChain {
description("Potential long-range attack: block not in finalized chain."),
display("Potential long-range attack: block not in finalized chain."),
}
/// Hash that is required for building CHT is missing.
MissingHashRequiredForCHT(cht_num: u64, block_number: u64) {
description("missed hash required for building CHT"),
display("Failed to get hash of block#{} for building CHT#{}", block_number, cht_num),
impl error::Error for Error {
fn source(&self) -> Option<&(error::Error + 'static)> {
match self {
Error::Consensus(e) => Some(e),
Error::Blockchain(e) => Some(e),
_ => None,
}
}
}
impl From<Box<state_machine::Error>> for Error {
fn from(e: Box<state_machine::Error>) -> Self {
ErrorKind::Execution(e).into()
impl From<String> for Error {
fn from(s: String) -> Self {
Error::Msg(s)
}
}
impl From<state_machine::backend::Void> for Error {
fn from(e: state_machine::backend::Void) -> Self {
match e {}
impl<'a> From<&'a str> for Error {
fn from(s: &'a str) -> Self {
Error::Msg(s.into())
}
}
impl Error {
/// Chain a blockchain error.
pub fn from_blockchain(e: Box<std::error::Error + Send>) -> Self {
ErrorKind::Blockchain(e).into()
pub fn from_blockchain(e: Box<Error>) -> Self {
Error::Blockchain(e)
}
/// Chain a state error.
pub fn from_state(e: Box<state_machine::Error + Send>) -> Self {
ErrorKind::Execution(e).into()
Error::Execution(e)
}
}
+7 -7
View File
@@ -207,7 +207,7 @@ impl<Block: BlockT> Blockchain<Block> {
pub fn set_head(&self, id: BlockId<Block>) -> error::Result<()> {
let header = match self.header(id)? {
Some(h) => h,
None => return Err(error::ErrorKind::UnknownBlock(format!("{}", id)).into()),
None => return Err(error::Error::UnknownBlock(format!("{}", id))),
};
self.apply_head(&header)
@@ -258,7 +258,7 @@ impl<Block: BlockT> Blockchain<Block> {
fn finalize_header(&self, id: BlockId<Block>, justification: Option<Justification>) -> error::Result<()> {
let hash = match self.header(id)? {
Some(h) => h.hash(),
None => return Err(error::ErrorKind::UnknownBlock(format!("{}", id)).into()),
None => return Err(error::Error::UnknownBlock(format!("{}", id))),
};
let mut storage = self.storage.write();
@@ -416,12 +416,12 @@ impl<Block: BlockT> light::blockchain::Storage<Block> for Blockchain<Block>
fn header_cht_root(&self, _cht_size: u64, block: NumberFor<Block>) -> error::Result<Block::Hash> {
self.storage.read().header_cht_roots.get(&block).cloned()
.ok_or_else(|| error::ErrorKind::Backend(format!("Header CHT for block {} not exists", block)).into())
.ok_or_else(|| error::Error::Backend(format!("Header CHT for block {} not exists", block)))
}
fn changes_trie_cht_root(&self, _cht_size: u64, block: NumberFor<Block>) -> error::Result<Block::Hash> {
self.storage.read().changes_trie_cht_roots.get(&block).cloned()
.ok_or_else(|| error::ErrorKind::Backend(format!("Changes trie CHT for block {} not exists", block)).into())
.ok_or_else(|| error::Error::Backend(format!("Changes trie CHT for block {} not exists", block)))
}
fn cache(&self) -> Option<Arc<blockchain::Cache<Block>>> {
@@ -665,7 +665,7 @@ where
match self.blockchain.id(block).and_then(|id| self.states.read().get(&id).cloned()) {
Some(state) => Ok(state),
None => Err(error::ErrorKind::UnknownBlock(format!("{}", block)).into()),
None => Err(error::Error::UnknownBlock(format!("{}", block))),
}
}
@@ -717,11 +717,11 @@ impl<H: Hasher> state_machine::ChangesTrieStorage<H> for ChangesTrieStorage<H> w
/// Check that genesis storage is valid.
pub fn check_genesis_storage(top: &StorageOverlay, children: &ChildrenStorageOverlay) -> error::Result<()> {
if top.iter().any(|(k, _)| well_known_keys::is_child_storage_key(k)) {
return Err(error::ErrorKind::GenesisInvalid.into());
return Err(error::Error::GenesisInvalid.into());
}
if children.keys().any(|child_key| !well_known_keys::is_child_storage_key(&child_key)) {
return Err(error::ErrorKind::GenesisInvalid.into());
return Err(error::Error::GenesisInvalid.into());
}
Ok(())
+2 -2
View File
@@ -85,11 +85,11 @@ impl<H, N> LeafSet<H, N> where
let raw_hash = &mut &key[prefix.len()..];
let hash = match Decode::decode(raw_hash) {
Some(hash) => hash,
None => return Err(error::ErrorKind::Backend("Error decoding hash".into()).into()),
None => return Err(error::Error::Backend("Error decoding hash".into())),
};
let number = match Decode::decode(&mut &value[..]) {
Some(number) => number,
None => return Err(error::ErrorKind::Backend("Error decoding number".into()).into()),
None => return Err(error::Error::Backend("Error decoding number".into())),
};
storage.entry(Reverse(number)).or_insert_with(Vec::new).push(hash);
}
+5 -5
View File
@@ -28,7 +28,7 @@ use runtime_primitives::traits::{Block as BlockT, NumberFor, Zero, Header};
use crate::in_mem::{self, check_genesis_storage};
use crate::backend::{AuxStore, Backend as ClientBackend, BlockImportOperation, RemoteBackend, NewBlockState};
use crate::blockchain::HeaderBackend as BlockchainHeaderBackend;
use crate::error::{Error as ClientError, ErrorKind as ClientErrorKind, Result as ClientResult};
use crate::error::{Error as ClientError, Result as ClientResult};
use crate::light::blockchain::{Blockchain, Storage as BlockchainStorage};
use crate::light::fetcher::{Fetcher, RemoteReadRequest};
use hash_db::Hasher;
@@ -208,7 +208,7 @@ impl<S, F, Block, H> ClientBackend<Block, H> for Backend<S, F, H> where
}
fn revert(&self, _n: NumberFor<Block>) -> ClientResult<NumberFor<Block>> {
Err(ClientErrorKind::NotAvailableOnLightClient.into())
Err(ClientError::NotAvailableOnLightClient.into())
}
}
@@ -323,13 +323,13 @@ where
let mut header = self.cached_header.read().clone();
if header.is_none() {
let cached_header = self.blockchain.upgrade()
.ok_or_else(|| ClientErrorKind::UnknownBlock(format!("{}", self.block)).into())
.ok_or_else(|| ClientError::UnknownBlock(format!("{}", self.block)))
.and_then(|blockchain| blockchain.expect_header(BlockId::Hash(self.block)))?;
header = Some(cached_header.clone());
*self.cached_header.write() = Some(cached_header);
}
self.fetcher.upgrade().ok_or(ClientErrorKind::NotAvailableOnLightClient)?
self.fetcher.upgrade().ok_or(ClientError::NotAvailableOnLightClient)?
.remote_read(RemoteReadRequest {
block: self.block,
header: header.expect("if block above guarantees that header is_some(); qed"),
@@ -340,7 +340,7 @@ where
}
fn child_storage(&self, _storage_key: &[u8], _key: &[u8]) -> ClientResult<Option<Vec<u8>>> {
Err(ClientErrorKind::NotAvailableOnLightClient.into())
Err(ClientError::NotAvailableOnLightClient.into())
}
fn for_keys_with_prefix<A: FnMut(&[u8])>(&self, _prefix: &[u8], _action: A) {
+12 -12
View File
@@ -29,7 +29,7 @@ use crate::backend::{AuxStore, NewBlockState};
use crate::blockchain::{Backend as BlockchainBackend, BlockStatus, Cache as BlockchainCache,
HeaderBackend as BlockchainHeaderBackend, Info as BlockchainInfo, ProvideCache};
use crate::cht;
use crate::error::{ErrorKind as ClientErrorKind, Result as ClientResult};
use crate::error::{Error as ClientError, Result as ClientResult};
use crate::light::fetcher::{Fetcher, RemoteHeaderRequest};
/// Light client blockchain storage.
@@ -114,7 +114,7 @@ impl<S, F, Block> BlockchainHeaderBackend<Block> for Blockchain<S, F> where Bloc
return Ok(None);
}
self.fetcher().upgrade().ok_or(ClientErrorKind::NotAvailableOnLightClient)?
self.fetcher().upgrade().ok_or(ClientError::NotAvailableOnLightClient)?
.remote_header(RemoteHeaderRequest {
cht_root: self.storage.header_cht_root(cht::SIZE, number)?,
block: number,
@@ -202,22 +202,22 @@ pub mod tests {
impl BlockchainHeaderBackend<Block> for DummyStorage {
fn header(&self, _id: BlockId<Block>) -> ClientResult<Option<Header>> {
Err(ClientErrorKind::Backend("Test error".into()).into())
Err(ClientError::Backend("Test error".into()))
}
fn info(&self) -> ClientResult<Info<Block>> {
Err(ClientErrorKind::Backend("Test error".into()).into())
Err(ClientError::Backend("Test error".into()))
}
fn status(&self, _id: BlockId<Block>) -> ClientResult<BlockStatus> {
Err(ClientErrorKind::Backend("Test error".into()).into())
Err(ClientError::Backend("Test error".into()))
}
fn number(&self, hash: Hash) -> ClientResult<Option<NumberFor<Block>>> {
if hash == Default::default() {
Ok(Some(Default::default()))
} else {
Err(ClientErrorKind::Backend("Test error".into()).into())
Err(ClientError::Backend("Test error".into()))
}
}
@@ -225,7 +225,7 @@ pub mod tests {
if number == 0 {
Ok(Some(Default::default()))
} else {
Err(ClientErrorKind::Backend("Test error".into()).into())
Err(ClientError::Backend("Test error".into()))
}
}
}
@@ -261,26 +261,26 @@ pub mod tests {
}
fn set_head(&self, _block: BlockId<Block>) -> ClientResult<()> {
Err(ClientErrorKind::Backend("Test error".into()).into())
Err(ClientError::Backend("Test error".into()))
}
fn finalize_header(&self, _block: BlockId<Block>) -> ClientResult<()> {
Err(ClientErrorKind::Backend("Test error".into()).into())
Err(ClientError::Backend("Test error".into()))
}
fn last_finalized(&self) -> ClientResult<Hash> {
Err(ClientErrorKind::Backend("Test error".into()).into())
Err(ClientError::Backend("Test error".into()))
}
fn header_cht_root(&self, _cht_size: u64, _block: u64) -> ClientResult<Hash> {
Err(ClientErrorKind::Backend("Test error".into()).into())
Err(ClientError::Backend("Test error".into()))
}
fn changes_trie_cht_root(&self, cht_size: u64, block: u64) -> ClientResult<Hash> {
cht::block_to_cht_number(cht_size, block)
.and_then(|cht_num| self.changes_tries_cht_roots.get(&cht_num))
.cloned()
.ok_or_else(|| ClientErrorKind::Backend(
.ok_or_else(|| ClientError::Backend(
format!("Test error: CHT for block #{} not found", block)
).into())
}
@@ -31,7 +31,7 @@ use hash_db::Hasher;
use crate::backend::RemoteBackend;
use crate::blockchain::Backend as ChainBackend;
use crate::call_executor::CallExecutor;
use crate::error::{Error as ClientError, ErrorKind as ClientErrorKind, Result as ClientResult};
use crate::error::{Error as ClientError, Result as ClientResult};
use crate::light::fetcher::{Fetcher, RemoteCallRequest};
use executor::{RuntimeVersion, NativeVersion};
use heapsize::HeapSizeOf;
@@ -126,7 +126,7 @@ where
) -> ClientResult<NativeOrEncoded<R>> where ExecutionManager<EM>: Clone {
// it is only possible to execute contextual call if changes are empty
if !changes.is_empty() || initialized_block.is_some() {
return Err(ClientErrorKind::NotAvailableOnLightClient.into());
return Err(ClientError::NotAvailableOnLightClient.into());
}
self.call(at, method, call_data, (&execution_manager).into(), side_effects_handler).map(NativeOrEncoded::Encoded)
@@ -135,7 +135,7 @@ where
fn runtime_version(&self, id: &BlockId<Block>) -> ClientResult<RuntimeVersion> {
let call_result = self.call(id, "version", &[], ExecutionStrategy::NativeElseWasm, NeverOffchainExt::new())?;
RuntimeVersion::decode(&mut call_result.as_slice())
.ok_or_else(|| ClientErrorKind::VersionInvalid.into())
.ok_or_else(|| ClientError::VersionInvalid.into())
}
fn call_at_state<
@@ -156,7 +156,7 @@ where
_native_call: Option<NC>,
_side_effects_handler: Option<&mut O>,
) -> ClientResult<(NativeOrEncoded<R>, S::Transaction, Option<MemoryDB<Blake2Hasher>>)> {
Err(ClientErrorKind::NotAvailableOnLightClient.into())
Err(ClientError::NotAvailableOnLightClient.into())
}
fn prove_at_trie_state<S: state_machine::TrieBackendStorage<Blake2Hasher>>(
@@ -166,7 +166,7 @@ where
_method: &str,
_call_data: &[u8]
) -> ClientResult<(Vec<u8>, Vec<Vec<u8>>)> {
Err(ClientErrorKind::NotAvailableOnLightClient.into())
Err(ClientError::NotAvailableOnLightClient.into())
}
fn native_runtime_version(&self) -> Option<&NativeVersion> {
@@ -275,7 +275,7 @@ impl<Block, B, Remote, Local> CallExecutor<Block, Blake2Hasher> for
ExecutionManager::NativeWhenPossible,
native_call,
side_effects_handler,
).map_err(|e| ClientErrorKind::Execution(Box::new(e.to_string())).into()),
).map_err(|e| ClientError::Execution(Box::new(e.to_string()))),
false => CallExecutor::contextual_call::<
_,
_,
@@ -296,7 +296,7 @@ impl<Block, B, Remote, Local> CallExecutor<Block, Blake2Hasher> for
ExecutionManager::NativeWhenPossible,
native_call,
side_effects_handler,
).map_err(|e| ClientErrorKind::Execution(Box::new(e.to_string())).into()),
).map_err(|e| ClientError::Execution(Box::new(e.to_string()))),
}
}
@@ -346,7 +346,7 @@ impl<Block, B, Remote, Local> CallExecutor<Block, Blake2Hasher> for
ExecutionManager::NativeWhenPossible,
native_call,
side_effects_handler,
).map_err(|e| ClientErrorKind::Execution(Box::new(e.to_string())).into())
).map_err(|e| ClientError::Execution(Box::new(e.to_string())))
}
fn prove_at_trie_state<S: state_machine::TrieBackendStorage<Blake2Hasher>>(
+7 -7
View File
@@ -29,7 +29,7 @@ use state_machine::{CodeExecutor, ChangesTrieRootsStorage, ChangesTrieAnchorBloc
TrieBackend, read_proof_check, key_changes_proof_check, create_proof_check_backend_storage};
use crate::cht;
use crate::error::{Error as ClientError, ErrorKind as ClientErrorKind, Result as ClientResult};
use crate::error::{Error as ClientError, Result as ClientResult};
use crate::light::blockchain::{Blockchain, Storage as BlockchainStorage};
use crate::light::call_executor::check_execution_proof;
@@ -193,7 +193,7 @@ impl<E, H, B: BlockT, S: BlockchainStorage<B>, F> LightDataChecker<E, H, B, S, F
// since we need roots of all changes tries for the range begin..max
// => remote node can't use max block greater that one that we have passed
if remote_proof.max_block > request.max_block.0 || remote_proof.max_block < request.last_block.0 {
return Err(ClientErrorKind::ChangesTrieAccessFailed(format!(
return Err(ClientError::ChangesTrieAccessFailed(format!(
"Invalid max_block used by the remote node: {}. Local: {}..{}..{}",
remote_proof.max_block, request.first_block.0, request.last_block.0, request.max_block.0,
)).into());
@@ -209,7 +209,7 @@ impl<E, H, B: BlockT, S: BlockchainStorage<B>, F> LightDataChecker<E, H, B, S, F
.map(|last_root| *last_root >= request.tries_roots.0)
.unwrap_or(false);
if is_extra_first_root || is_extra_last_root {
return Err(ClientErrorKind::ChangesTrieAccessFailed(format!(
return Err(ClientError::ChangesTrieAccessFailed(format!(
"Extra changes tries roots proofs provided by the remote node: [{:?}..{:?}]. Expected in range: [{}; {})",
remote_proof.roots.keys().next(), remote_proof.roots.keys().next_back(),
request.first_block.0, request.tries_roots.0,
@@ -247,7 +247,7 @@ impl<E, H, B: BlockT, S: BlockchainStorage<B>, F> LightDataChecker<E, H, B, S, F
remote_max_block.as_(),
&request.key)
.map(|pairs| pairs.into_iter().map(|(b, x)| (As::sa(b), x)).collect())
.map_err(|err| ClientErrorKind::ChangesTrieAccessFailed(err).into())
.map_err(|err| ClientError::ChangesTrieAccessFailed(err))
}
/// Check CHT-based proof for changes tries roots.
@@ -283,7 +283,7 @@ impl<E, H, B: BlockT, S: BlockchainStorage<B>, F> LightDataChecker<E, H, B, S, F
let mut cht_root = H::Out::default();
cht_root.as_mut().copy_from_slice(local_cht_root.as_ref());
if !storage.contains(&cht_root, &[]) {
return Err(ClientErrorKind::InvalidCHTProof.into());
return Err(ClientError::InvalidCHTProof.into());
}
// check proof for single changes trie root
@@ -320,7 +320,7 @@ impl<E, Block, H, S, F> FetchChecker<Block> for LightDataChecker<E, H, Block, S,
remote_proof: Vec<Vec<u8>>
) -> ClientResult<Block::Header> {
let remote_header = remote_header.ok_or_else(||
ClientError::from(ClientErrorKind::InvalidCHTProof))?;
ClientError::from(ClientError::InvalidCHTProof))?;
let remote_header_hash = remote_header.hash();
cht::check_proof::<Block::Header, H>(
request.cht_root,
@@ -473,7 +473,7 @@ pub mod tests {
let builder = remote_client.new_block().unwrap();
remote_client.import(BlockOrigin::Own, builder.bake().unwrap()).unwrap();
local_headers_hashes.push(remote_client.block_hash(i + 1)
.map_err(|_| ClientErrorKind::Backend("TestError".into()).into()));
.map_err(|_| ClientError::Backend("TestError".into())));
}
// 'fetch' header proof from remote node