mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-13 15:11:03 +00:00
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:
committed by
Bastian Köcher
parent
1e0c1d8850
commit
7f59cdb900
@@ -5,7 +5,7 @@ authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
error-chain = { version = "0.12", optional = true }
|
||||
derive_more = { version = "0.14.0", optional = true }
|
||||
fnv = { version = "1.0", optional = true }
|
||||
log = { version = "0.4", optional = true }
|
||||
parking_lot = { version = "0.7.1", optional = true }
|
||||
@@ -44,7 +44,7 @@ std = [
|
||||
"hash-db/std",
|
||||
"consensus",
|
||||
"parking_lot",
|
||||
"error-chain",
|
||||
"derive_more",
|
||||
"fnv",
|
||||
"log",
|
||||
"hex",
|
||||
|
||||
+3
-3
@@ -43,7 +43,7 @@ use std::collections::BTreeSet;
|
||||
|
||||
use log::warn;
|
||||
|
||||
use client::error::{ErrorKind as ClientErrorKind, Result as ClientResult};
|
||||
use client::error::{Error as ClientError, Result as ClientResult};
|
||||
use runtime_primitives::traits::{Block as BlockT, NumberFor, As, Zero};
|
||||
|
||||
use crate::cache::{CacheItemT, ComplexBlockId};
|
||||
@@ -537,10 +537,10 @@ mod chain {
|
||||
) -> ClientResult<bool> {
|
||||
let (begin, end) = if block1 > block2 { (block2, block1) } else { (block1, block2) };
|
||||
let mut current = storage.read_header(&end.hash)?
|
||||
.ok_or_else(|| ClientErrorKind::UnknownBlock(format!("{}", end.hash)))?;
|
||||
.ok_or_else(|| ClientError::UnknownBlock(format!("{}", end.hash)))?;
|
||||
while *current.number() > begin.number {
|
||||
current = storage.read_header(current.parent_hash())?
|
||||
.ok_or_else(|| ClientErrorKind::UnknownBlock(format!("{}", current.parent_hash())))?;
|
||||
.ok_or_else(|| ClientError::UnknownBlock(format!("{}", current.parent_hash())))?;
|
||||
}
|
||||
|
||||
Ok(begin.hash == current.hash())
|
||||
|
||||
+9
-9
@@ -20,7 +20,7 @@ use std::sync::Arc;
|
||||
|
||||
use kvdb::{KeyValueDB, DBTransaction};
|
||||
|
||||
use client::error::{Error as ClientError, ErrorKind as ClientErrorKind, Result as ClientResult};
|
||||
use client::error::{Error as ClientError, Result as ClientResult};
|
||||
use parity_codec::{Encode, Decode};
|
||||
use runtime_primitives::generic::BlockId;
|
||||
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, NumberFor};
|
||||
@@ -59,7 +59,7 @@ pub trait Storage<Block: BlockT, T: CacheItemT> {
|
||||
self.read_entry(at)
|
||||
.and_then(|entry| entry
|
||||
.ok_or_else(|| ClientError::from(
|
||||
ClientErrorKind::Backend(format!("Referenced cache entry at {:?} is not found", at)))))
|
||||
ClientError::Backend(format!("Referenced cache entry at {:?} is not found", at)))))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,7 +151,7 @@ impl<Block: BlockT, T: CacheItemT> Storage<Block, T> for DbStorage {
|
||||
.map_err(db_err)
|
||||
.and_then(|entry| match entry {
|
||||
Some(entry) => StorageEntry::<Block, T>::decode(&mut &entry[..])
|
||||
.ok_or_else(|| ClientErrorKind::Backend("Failed to decode cache entry".into()).into())
|
||||
.ok_or_else(|| ClientError::Backend("Failed to decode cache entry".into()))
|
||||
.map(Some),
|
||||
None => Ok(None),
|
||||
})
|
||||
@@ -236,9 +236,9 @@ mod meta {
|
||||
pub fn decode<Block: BlockT>(encoded: &[u8]) -> ClientResult<Metadata<Block>> {
|
||||
let input = &mut &*encoded;
|
||||
let finalized: Option<ComplexBlockId<Block>> = Decode::decode(input)
|
||||
.ok_or_else(|| ClientError::from(ClientErrorKind::Backend("Error decoding cache meta".into())))?;
|
||||
.ok_or_else(|| ClientError::from(ClientError::Backend("Error decoding cache meta".into())))?;
|
||||
let unfinalized: Vec<ComplexBlockId<Block>> = Decode::decode(input)
|
||||
.ok_or_else(|| ClientError::from(ClientErrorKind::Backend("Error decoding cache meta".into())))?;
|
||||
.ok_or_else(|| ClientError::from(ClientError::Backend("Error decoding cache meta".into())))?;
|
||||
|
||||
Ok(Metadata { finalized, unfinalized })
|
||||
}
|
||||
@@ -253,19 +253,19 @@ pub mod tests {
|
||||
|
||||
impl<Block: BlockT, T: CacheItemT> Storage<Block, T> for FaultyStorage {
|
||||
fn read_id(&self, _at: NumberFor<Block>) -> ClientResult<Option<Block::Hash>> {
|
||||
Err(ClientErrorKind::Backend("TestError".into()).into())
|
||||
Err(ClientError::Backend("TestError".into()))
|
||||
}
|
||||
|
||||
fn read_header(&self, _at: &Block::Hash) -> ClientResult<Option<Block::Header>> {
|
||||
Err(ClientErrorKind::Backend("TestError".into()).into())
|
||||
Err(ClientError::Backend("TestError".into()))
|
||||
}
|
||||
|
||||
fn read_meta(&self) -> ClientResult<Metadata<Block>> {
|
||||
Err(ClientErrorKind::Backend("TestError".into()).into())
|
||||
Err(ClientError::Backend("TestError".into()))
|
||||
}
|
||||
|
||||
fn read_entry(&self, _at: &ComplexBlockId<Block>) -> ClientResult<Option<StorageEntry<Block, T>>> {
|
||||
Err(ClientErrorKind::Backend("TestError".into()).into())
|
||||
Err(ClientError::Backend("TestError".into()))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -225,7 +225,7 @@ impl<Block: BlockT> client::blockchain::Backend<Block> for BlockchainDb<Block> {
|
||||
match read_db(&*self.db, columns::KEY_LOOKUP, columns::BODY, id)? {
|
||||
Some(body) => match Decode::decode(&mut &body[..]) {
|
||||
Some(body) => Ok(Some(body)),
|
||||
None => return Err(client::error::ErrorKind::Backend("Error decoding body".into()).into()),
|
||||
None => return Err(client::error::Error::Backend("Error decoding body".into())),
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
@@ -235,7 +235,7 @@ impl<Block: BlockT> client::blockchain::Backend<Block> for BlockchainDb<Block> {
|
||||
match read_db(&*self.db, columns::KEY_LOOKUP, columns::JUSTIFICATION, id)? {
|
||||
Some(justification) => match Decode::decode(&mut &justification[..]) {
|
||||
Some(justification) => Ok(Some(justification)),
|
||||
None => return Err(client::error::ErrorKind::Backend("Error decoding justification".into()).into()),
|
||||
None => return Err(client::error::Error::Backend("Error decoding justification".into())),
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
@@ -326,14 +326,14 @@ where Block: BlockT<Hash=H256>,
|
||||
fn reset_storage(&mut self, mut top: StorageOverlay, children: ChildrenStorageOverlay) -> Result<H256, client::error::Error> {
|
||||
|
||||
if top.iter().any(|(k, _)| well_known_keys::is_child_storage_key(k)) {
|
||||
return Err(client::error::ErrorKind::GenesisInvalid.into());
|
||||
return Err(client::error::Error::GenesisInvalid.into());
|
||||
}
|
||||
|
||||
let mut transaction: PrefixedMemoryDB<Blake2Hasher> = Default::default();
|
||||
|
||||
for (child_key, child_map) in children {
|
||||
if !well_known_keys::is_child_storage_key(&child_key) {
|
||||
return Err(client::error::ErrorKind::GenesisInvalid.into());
|
||||
return Err(client::error::Error::GenesisInvalid.into());
|
||||
}
|
||||
|
||||
let (root, is_default, update) = self.old_state.child_storage_root(&child_key, child_map.into_iter().map(|(k, v)| (k, Some(v))));
|
||||
@@ -684,7 +684,7 @@ impl<Block: BlockT<Hash=H256>> Backend<Block> {
|
||||
(&r.number, &r.hash)
|
||||
);
|
||||
|
||||
return Err(::client::error::ErrorKind::NotInFinalizedChain.into());
|
||||
return Err(::client::error::Error::NotInFinalizedChain.into());
|
||||
}
|
||||
|
||||
retracted.push(r.hash.clone());
|
||||
@@ -726,7 +726,7 @@ impl<Block: BlockT<Hash=H256>> Backend<Block> {
|
||||
) -> Result<(), client::error::Error> {
|
||||
let last_finalized = last_finalized.unwrap_or_else(|| self.blockchain.meta.read().finalized_hash);
|
||||
if *header.parent_hash() != last_finalized {
|
||||
return Err(::client::error::ErrorKind::NonSequentialFinalization(
|
||||
return Err(::client::error::Error::NonSequentialFinalization(
|
||||
format!("Last finalized {:?} not parent of {:?}", last_finalized, header.hash()),
|
||||
).into());
|
||||
}
|
||||
@@ -926,7 +926,7 @@ impl<Block: BlockT<Hash=H256>> Backend<Block> {
|
||||
(number.clone(), hash.clone())
|
||||
)?;
|
||||
} else {
|
||||
return Err(client::error::ErrorKind::UnknownBlock(format!("Cannot set head {:?}", set_head)).into())
|
||||
return Err(client::error::Error::UnknownBlock(format!("Cannot set head {:?}", set_head)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1138,12 +1138,12 @@ impl<Block> client::backend::Backend<Block, Blake2Hasher> for Backend<Block> whe
|
||||
Some(commit) => {
|
||||
apply_state_commit(&mut transaction, commit);
|
||||
let removed = self.blockchain.header(BlockId::Number(best))?.ok_or_else(
|
||||
|| client::error::ErrorKind::UnknownBlock(
|
||||
|| client::error::Error::UnknownBlock(
|
||||
format!("Error reverting to {}. Block hash not found.", best)))?;
|
||||
|
||||
best -= As::sa(1); // prev block
|
||||
let hash = self.blockchain.hash(best)?.ok_or_else(
|
||||
|| client::error::ErrorKind::UnknownBlock(
|
||||
|| client::error::Error::UnknownBlock(
|
||||
format!("Error reverting to {}. Block hash not found.", best)))?;
|
||||
let key = utils::number_and_hash_to_lookup_key(best.clone(), &hash);
|
||||
transaction.put(columns::META, meta_keys::BEST_BLOCK, &key);
|
||||
@@ -1185,10 +1185,10 @@ impl<Block> client::backend::Backend<Block, Blake2Hasher> for Backend<Block> whe
|
||||
let state = DbState::new(self.storage.clone(), root);
|
||||
Ok(CachingState::new(state, self.shared_cache.clone(), Some(hash)))
|
||||
} else {
|
||||
Err(client::error::ErrorKind::UnknownBlock(format!("State already discarded for {:?}", block)).into())
|
||||
Err(client::error::Error::UnknownBlock(format!("State already discarded for {:?}", block)))
|
||||
}
|
||||
},
|
||||
Ok(None) => Err(client::error::ErrorKind::UnknownBlock(format!("Unknown state for block {:?}", block)).into()),
|
||||
Ok(None) => Err(client::error::Error::UnknownBlock(format!("Unknown state for block {:?}", block))),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ use client::blockchain::{BlockStatus, Cache as BlockchainCache,
|
||||
HeaderBackend as BlockchainHeaderBackend, Info as BlockchainInfo};
|
||||
use client::cht;
|
||||
use client::leaves::{LeafSet, FinalizationDisplaced};
|
||||
use client::error::{ErrorKind as ClientErrorKind, Result as ClientResult};
|
||||
use client::error::{Error as ClientError, Result as ClientResult};
|
||||
use client::light::blockchain::Storage as LightBlockchainStorage;
|
||||
use parity_codec::{Decode, Encode};
|
||||
use primitives::Blake2Hasher;
|
||||
@@ -256,7 +256,7 @@ impl<Block: BlockT> LightStorage<Block> {
|
||||
) -> ClientResult<()> {
|
||||
let meta = self.meta.read();
|
||||
if &meta.finalized_hash != header.parent_hash() {
|
||||
return Err(::client::error::ErrorKind::NonSequentialFinalization(
|
||||
return Err(::client::error::Error::NonSequentialFinalization(
|
||||
format!("Last finalized {:?} not parent of {:?}",
|
||||
meta.finalized_hash, hash),
|
||||
).into())
|
||||
@@ -330,7 +330,7 @@ impl<Block: BlockT> LightStorage<Block> {
|
||||
cht_size: u64,
|
||||
block: NumberFor<Block>
|
||||
) -> ClientResult<Block::Hash> {
|
||||
let no_cht_for_block = || ClientErrorKind::Backend(format!("CHT for block {} not exists", block)).into();
|
||||
let no_cht_for_block = || ClientError::Backend(format!("CHT for block {} not exists", block));
|
||||
|
||||
let cht_number = cht::block_to_cht_number(cht_size, block).ok_or_else(no_cht_for_block)?;
|
||||
let cht_start = cht::start_number(cht_size, cht_number);
|
||||
@@ -474,7 +474,7 @@ impl<Block> LightBlockchainStorage<Block> for LightStorage<Block>
|
||||
self.db.write(transaction).map_err(db_err)?;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ClientErrorKind::UnknownBlock(format!("Cannot set head {:?}", id)).into())
|
||||
Err(ClientError::UnknownBlock(format!("Cannot set head {:?}", id)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -514,7 +514,7 @@ impl<Block> LightBlockchainStorage<Block> for LightStorage<Block>
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ClientErrorKind::UnknownBlock(format!("Cannot finalize block {:?}", id)).into())
|
||||
Err(ClientError::UnknownBlock(format!("Cannot finalize block {:?}", id)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ pub fn number_and_hash_to_lookup_key<N, H>(number: N, hash: H) -> Vec<u8> where
|
||||
/// all block lookup keys start with the block number.
|
||||
pub fn lookup_key_to_number<N>(key: &[u8]) -> client::error::Result<N> where N: As<u64> {
|
||||
if key.len() < 4 {
|
||||
return Err(client::error::ErrorKind::Backend("Invalid block key".into()).into());
|
||||
return Err(client::error::Error::Backend("Invalid block key".into()));
|
||||
}
|
||||
Ok((key[0] as u64) << 24
|
||||
| (key[1] as u64) << 16
|
||||
@@ -187,21 +187,21 @@ pub fn block_id_to_lookup_key<Block>(
|
||||
/// Maps database error to client error
|
||||
pub fn db_err(err: io::Error) -> client::error::Error {
|
||||
use std::error::Error;
|
||||
client::error::ErrorKind::Backend(err.description().into()).into()
|
||||
client::error::Error::Backend(err.description().into())
|
||||
}
|
||||
|
||||
/// Open RocksDB database.
|
||||
pub fn open_database(config: &DatabaseSettings, col_meta: Option<u32>, db_type: &str) -> client::error::Result<Arc<KeyValueDB>> {
|
||||
let mut db_config = DatabaseConfig::with_columns(Some(NUM_COLUMNS));
|
||||
db_config.memory_budget = config.cache_size;
|
||||
let path = config.path.to_str().ok_or_else(|| client::error::ErrorKind::Backend("Invalid database path".into()))?;
|
||||
let path = config.path.to_str().ok_or_else(|| client::error::Error::Backend("Invalid database path".into()))?;
|
||||
let db = Database::open(&db_config, &path).map_err(db_err)?;
|
||||
|
||||
// check database type
|
||||
match db.get(col_meta, meta_keys::TYPE).map_err(db_err)? {
|
||||
Some(stored_type) => {
|
||||
if db_type.as_bytes() != &*stored_type {
|
||||
return Err(client::error::ErrorKind::Backend(
|
||||
return Err(client::error::Error::Backend(
|
||||
format!("Unexpected database type. Expected: {}", db_type)).into());
|
||||
}
|
||||
},
|
||||
@@ -237,7 +237,7 @@ pub fn read_header<Block: BlockT>(
|
||||
Some(header) => match Block::Header::decode(&mut &header[..]) {
|
||||
Some(header) => Ok(Some(header)),
|
||||
None => return Err(
|
||||
client::error::ErrorKind::Backend("Error decoding header".into()).into()
|
||||
client::error::Error::Backend("Error decoding header".into())
|
||||
),
|
||||
}
|
||||
None => Ok(None),
|
||||
@@ -252,7 +252,7 @@ pub fn require_header<Block: BlockT>(
|
||||
id: BlockId<Block>,
|
||||
) -> client::error::Result<Block::Header> {
|
||||
read_header(db, col_index, col, id)
|
||||
.and_then(|header| header.ok_or_else(|| client::error::ErrorKind::UnknownBlock(format!("{}", id)).into()))
|
||||
.and_then(|header| header.ok_or_else(|| client::error::Error::UnknownBlock(format!("{}", id))))
|
||||
}
|
||||
|
||||
/// Read meta from the database.
|
||||
@@ -266,7 +266,7 @@ pub fn read_meta<Block>(db: &KeyValueDB, col_meta: Option<u32>, col_header: Opti
|
||||
let genesis_hash: Block::Hash = match db.get(col_meta, meta_keys::GENESIS_HASH).map_err(db_err)? {
|
||||
Some(h) => match Decode::decode(&mut &h[..]) {
|
||||
Some(h) => h,
|
||||
None => return Err(client::error::ErrorKind::Backend("Error decoding genesis hash".into()).into()),
|
||||
None => return Err(client::error::Error::Backend("Error decoding genesis hash".into())),
|
||||
},
|
||||
None => return Ok(Meta {
|
||||
best_hash: Default::default(),
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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<
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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_()))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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))),
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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(())
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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>>(
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user