Remove all (non-dev) client references from frame, activate dependency enforcer (#4184)

* Move transaction pool to primitives

* move backend, errors into primitives

* remove unused client depencies

* Move rpc-api into primitives

* Move peerset back to client

* Move rpc/api back to client, move palette/support/rpc into utils

* move support-rpc into subfolder

* move system-rpc into utils

* move transaction-pool  and -graph back into client

* fix broken imports

* Clean up test primitives

* Make support test utils independent of frame

* remove unnecessary node dependencies from service

* Reactivate dependency script:
 - only enforce the now achieved status quo will remain
 - allow for primitives to depend on /client for now without failing
 - more discriptive error message so people understand, what it wants
 - minor fix to differentiative between ../client and /client (which may be a subfolder)
 - don't allow this to fail anylonger.

* fix doc comment

* 'Should not' rather than 'must not'.

* Revert unwanted dependency changes

* fix faulty import

* fixup derive_more version

* fix wrong import path
This commit is contained in:
Benjamin Kampmann
2019-11-26 21:38:28 +01:00
committed by GitHub
parent b2aab98e69
commit bd652793db
130 changed files with 836 additions and 816 deletions
+23 -23
View File
@@ -28,9 +28,9 @@ use crate::{
blockchain::{
Backend as BlockchainBackend, well_known_cache_keys
},
error,
light::RemoteBlockchain,
};
use sp_blockchain;
use consensus::BlockOrigin;
use hash_db::Hasher;
use parking_lot::RwLock;
@@ -116,7 +116,7 @@ pub trait BlockImportOperation<Block, H> where
/// Returns pending state.
///
/// Returns None for backends with locally-unavailable state data.
fn state(&self) -> error::Result<Option<&Self::State>>;
fn state(&self) -> sp_blockchain::Result<Option<&Self::State>>;
/// Append block data to the transaction.
fn set_block_data(
@@ -125,37 +125,37 @@ pub trait BlockImportOperation<Block, H> where
body: Option<Vec<Block::Extrinsic>>,
justification: Option<Justification>,
state: NewBlockState,
) -> error::Result<()>;
) -> sp_blockchain::Result<()>;
/// Update cached data.
fn update_cache(&mut self, cache: HashMap<well_known_cache_keys::Id, Vec<u8>>);
/// Inject storage data into the database.
fn update_db_storage(&mut self, update: <Self::State as StateBackend<H>>::Transaction) -> error::Result<()>;
fn update_db_storage(&mut self, update: <Self::State as StateBackend<H>>::Transaction) -> sp_blockchain::Result<()>;
/// Inject storage data into the database replacing any existing data.
fn reset_storage(&mut self, top: StorageOverlay, children: ChildrenStorageOverlay) -> error::Result<H::Out>;
fn reset_storage(&mut self, top: StorageOverlay, children: ChildrenStorageOverlay) -> sp_blockchain::Result<H::Out>;
/// Set storage changes.
fn update_storage(
&mut self,
update: StorageCollection,
child_update: ChildStorageCollection,
) -> error::Result<()>;
) -> sp_blockchain::Result<()>;
/// Inject changes trie data into the database.
fn update_changes_trie(&mut self, update: ChangesTrieTransaction<H, NumberFor<Block>>) -> error::Result<()>;
fn update_changes_trie(&mut self, update: ChangesTrieTransaction<H, NumberFor<Block>>) -> sp_blockchain::Result<()>;
/// Insert auxiliary keys.
///
/// Values are `None` if should be deleted.
fn insert_aux<I>(&mut self, ops: I) -> error::Result<()>
fn insert_aux<I>(&mut self, ops: I) -> sp_blockchain::Result<()>
where I: IntoIterator<Item=(Vec<u8>, Option<Vec<u8>>)>;
/// Mark a block as finalized.
fn mark_finalized(&mut self, id: BlockId<Block>, justification: Option<Justification>) -> error::Result<()>;
fn mark_finalized(&mut self, id: BlockId<Block>, justification: Option<Justification>) -> sp_blockchain::Result<()>;
/// Mark a block as new head. If both block import and set head are specified, set head overrides block import's best block rule.
fn mark_head(&mut self, id: BlockId<Block>) -> error::Result<()>;
fn mark_head(&mut self, id: BlockId<Block>) -> sp_blockchain::Result<()>;
}
/// Finalize Facilities
@@ -175,7 +175,7 @@ pub trait Finalizer<Block: BlockT, H: Hasher<Out=Block::Hash>, B: Backend<Block,
id: BlockId<Block>,
justification: Option<Justification>,
notify: bool,
) -> error::Result<()>;
) -> sp_blockchain::Result<()>;
/// Finalize a block.
@@ -196,7 +196,7 @@ pub trait Finalizer<Block: BlockT, H: Hasher<Out=Block::Hash>, B: Backend<Block,
id: BlockId<Block>,
justification: Option<Justification>,
notify: bool,
) -> error::Result<()>;
) -> sp_blockchain::Result<()>;
}
@@ -211,10 +211,10 @@ pub trait AuxStore {
'c: 'a,
I: IntoIterator<Item=&'a(&'c [u8], &'c [u8])>,
D: IntoIterator<Item=&'a &'b [u8]>,
>(&self, insert: I, delete: D) -> error::Result<()>;
>(&self, insert: I, delete: D) -> sp_blockchain::Result<()>;
/// Query auxiliary data from key-value store.
fn get_aux(&self, key: &[u8]) -> error::Result<Option<Vec<u8>>>;
fn get_aux(&self, key: &[u8]) -> sp_blockchain::Result<Option<Vec<u8>>>;
}
/// Client backend.
@@ -245,18 +245,18 @@ pub trait Backend<Block, H>: AuxStore + Send + Sync where
/// Begin a new block insertion transaction with given parent block id.
///
/// When constructing the genesis, this is called with all-zero hash.
fn begin_operation(&self) -> error::Result<Self::BlockImportOperation>;
fn begin_operation(&self) -> sp_blockchain::Result<Self::BlockImportOperation>;
/// Note an operation to contain state transition.
fn begin_state_operation(&self, operation: &mut Self::BlockImportOperation, block: BlockId<Block>) -> error::Result<()>;
fn begin_state_operation(&self, operation: &mut Self::BlockImportOperation, block: BlockId<Block>) -> sp_blockchain::Result<()>;
/// Commit block insertion.
fn commit_operation(&self, transaction: Self::BlockImportOperation) -> error::Result<()>;
fn commit_operation(&self, transaction: Self::BlockImportOperation) -> sp_blockchain::Result<()>;
/// Finalize block with given Id.
///
/// This should only be called if the parent of the given block has been finalized.
fn finalize_block(&self, block: BlockId<Block>, justification: Option<Justification>) -> error::Result<()>;
fn finalize_block(&self, block: BlockId<Block>, justification: Option<Justification>) -> sp_blockchain::Result<()>;
/// Returns reference to blockchain backend.
fn blockchain(&self) -> &Self::Blockchain;
@@ -276,17 +276,17 @@ pub trait Backend<Block, H>: AuxStore + Send + Sync where
}
/// Returns state backend with post-state of given block.
fn state_at(&self, block: BlockId<Block>) -> error::Result<Self::State>;
fn state_at(&self, block: BlockId<Block>) -> sp_blockchain::Result<Self::State>;
/// Destroy state and save any useful data, such as cache.
fn destroy_state(&self, _state: Self::State) -> error::Result<()> {
fn destroy_state(&self, _state: Self::State) -> sp_blockchain::Result<()> {
Ok(())
}
/// Attempts to revert the chain by `n` blocks.
///
/// Returns the number of blocks that were successfully reverted.
fn revert(&self, n: NumberFor<Block>) -> error::Result<NumberFor<Block>>;
fn revert(&self, n: NumberFor<Block>) -> sp_blockchain::Result<NumberFor<Block>>;
/// Insert auxiliary data into key-value store.
fn insert_aux<
@@ -295,12 +295,12 @@ pub trait Backend<Block, H>: AuxStore + Send + Sync where
'c: 'a,
I: IntoIterator<Item=&'a(&'c [u8], &'c [u8])>,
D: IntoIterator<Item=&'a &'b [u8]>,
>(&self, insert: I, delete: D) -> error::Result<()>
>(&self, insert: I, delete: D) -> sp_blockchain::Result<()>
{
AuxStore::insert_aux(self, insert, delete)
}
/// Query auxiliary data from key-value store.
fn get_aux(&self, key: &[u8]) -> error::Result<Option<Vec<u8>>> {
fn get_aux(&self, key: &[u8]) -> sp_blockchain::Result<Option<Vec<u8>>> {
AuxStore::get_aux(self, key)
}
-275
View File
@@ -1,275 +0,0 @@
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Substrate blockchain trait
use std::sync::Arc;
use sr_primitives::traits::{Block as BlockT, Header as HeaderT, NumberFor};
use sr_primitives::generic::BlockId;
use sr_primitives::Justification;
use log::warn;
use parking_lot::RwLock;
use header_metadata::HeaderMetadata;
use crate::error::{Error, Result};
/// Blockchain database header backend. Does not perform any validation.
pub trait HeaderBackend<Block: BlockT>: Send + Sync {
/// Get block header. Returns `None` if block is not found.
fn header(&self, id: BlockId<Block>) -> Result<Option<Block::Header>>;
/// Get blockchain info.
fn info(&self) -> Info<Block>;
/// Get block status.
fn status(&self, id: BlockId<Block>) -> Result<BlockStatus>;
/// Get block number by hash. Returns `None` if the header is not in the chain.
fn number(&self, hash: Block::Hash) -> Result<Option<<<Block as BlockT>::Header as HeaderT>::Number>>;
/// Get block hash by number. Returns `None` if the header is not in the chain.
fn hash(&self, number: NumberFor<Block>) -> Result<Option<Block::Hash>>;
/// Convert an arbitrary block ID into a block hash.
fn block_hash_from_id(&self, id: &BlockId<Block>) -> Result<Option<Block::Hash>> {
match *id {
BlockId::Hash(h) => Ok(Some(h)),
BlockId::Number(n) => self.hash(n),
}
}
/// Convert an arbitrary block ID into a block hash.
fn block_number_from_id(&self, id: &BlockId<Block>) -> Result<Option<NumberFor<Block>>> {
match *id {
BlockId::Hash(_) => Ok(self.header(*id)?.map(|h| h.number().clone())),
BlockId::Number(n) => Ok(Some(n)),
}
}
/// 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(|| 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(|| 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(|| Error::UnknownBlock(format!("{}", id))))
}
}
/// Blockchain database backend. Does not perform any validation.
pub trait Backend<Block: BlockT>: HeaderBackend<Block> + HeaderMetadata<Block, Error=Error> {
/// Get block body. Returns `None` if block is not found.
fn body(&self, id: BlockId<Block>) -> Result<Option<Vec<<Block as BlockT>::Extrinsic>>>;
/// Get block justification. Returns `None` if justification does not exist.
fn justification(&self, id: BlockId<Block>) -> Result<Option<Justification>>;
/// Get last finalized block hash.
fn last_finalized(&self) -> Result<Block::Hash>;
/// Returns data cache reference, if it is enabled on this backend.
fn cache(&self) -> Option<Arc<dyn Cache<Block>>>;
/// Returns hashes of all blocks that are leaves of the block tree.
/// in other words, that have no children, are chain heads.
/// Results must be ordered best (longest, highest) chain first.
fn leaves(&self) -> Result<Vec<Block::Hash>>;
/// Return hashes of all blocks that are children of the block with `parent_hash`.
fn children(&self, parent_hash: Block::Hash) -> Result<Vec<Block::Hash>>;
/// Get the most recent block hash of the best (longest) chains
/// that contain block with the given `target_hash`.
///
/// The search space is always limited to blocks which are in the finalized
/// chain or descendents of it.
///
/// If `maybe_max_block_number` is `Some(max_block_number)`
/// the search is limited to block `numbers <= max_block_number`.
/// in other words as if there were no blocks greater `max_block_number`.
/// Returns `Ok(None)` if `target_hash` is not found in search space.
/// TODO: document time complexity of this, see [#1444](https://github.com/paritytech/substrate/issues/1444)
fn best_containing(
&self,
target_hash: Block::Hash,
maybe_max_number: Option<NumberFor<Block>>,
import_lock: &RwLock<()>,
) -> Result<Option<Block::Hash>> {
let target_header = {
match self.header(BlockId::Hash(target_hash))? {
Some(x) => x,
// target not in blockchain
None => { return Ok(None); },
}
};
if let Some(max_number) = maybe_max_number {
// target outside search range
if target_header.number() > &max_number {
return Ok(None);
}
}
let leaves = {
// ensure no blocks are imported during this code block.
// an import could trigger a reorg which could change the canonical chain.
// we depend on the canonical chain staying the same during this code block.
let _import_guard = import_lock.read();
let info = self.info();
// this can be `None` if the best chain is shorter than the target header.
let maybe_canon_hash = self.hash(*target_header.number())?;
if maybe_canon_hash.as_ref() == Some(&target_hash) {
// if a `max_number` is given we try to fetch the block at the
// given depth, if it doesn't exist or `max_number` is not
// provided, we continue to search from all leaves below.
if let Some(max_number) = maybe_max_number {
if let Some(header) = self.hash(max_number)? {
return Ok(Some(header));
}
}
} else if info.finalized_number >= *target_header.number() {
// header is on a dead fork.
return Ok(None);
}
self.leaves()?
};
// for each chain. longest chain first. shortest last
for leaf_hash in leaves {
// start at the leaf
let mut current_hash = leaf_hash;
// if search is not restricted then the leaf is the best
let mut best_hash = leaf_hash;
// go backwards entering the search space
// waiting until we are <= max_number
if let Some(max_number) = maybe_max_number {
loop {
let current_header = self.header(BlockId::Hash(current_hash.clone()))?
.ok_or_else(|| Error::from(format!("failed to get header for hash {}", current_hash)))?;
if current_header.number() <= &max_number {
best_hash = current_header.hash();
break;
}
current_hash = *current_header.parent_hash();
}
}
// go backwards through the chain (via parent links)
loop {
// until we find target
if current_hash == target_hash {
return Ok(Some(best_hash));
}
let current_header = self.header(BlockId::Hash(current_hash.clone()))?
.ok_or_else(|| Error::from(format!("failed to get header for hash {}", current_hash)))?;
// stop search in this chain once we go below the target's block number
if current_header.number() < target_header.number() {
break;
}
current_hash = *current_header.parent_hash();
}
}
// header may be on a dead fork -- the only leaves that are considered are
// those which can still be finalized.
//
// FIXME #1558 only issue this warning when not on a dead fork
warn!(
"Block {:?} exists in chain but not found when following all \
leaves backwards. Number limit = {:?}",
target_hash,
maybe_max_number,
);
Ok(None)
}
}
/// Provides access to the optional cache.
pub trait ProvideCache<Block: BlockT> {
/// Returns data cache reference, if it is enabled on this backend.
fn cache(&self) -> Option<Arc<dyn Cache<Block>>>;
}
/// Blockchain optional data cache.
pub trait Cache<Block: BlockT>: Send + Sync {
/// Initialize genesis value for the given cache.
///
/// The operation should be performed once before anything else is inserted in the cache.
/// Otherwise cache may end up in inconsistent state.
fn initialize(&self, key: &well_known_cache_keys::Id, value_at_genesis: Vec<u8>) -> Result<()>;
/// Returns cached value by the given key.
///
/// Returned tuple is the range where value has been active and the value itself.
fn get_at(
&self,
key: &well_known_cache_keys::Id,
block: &BlockId<Block>,
) -> Option<((NumberFor<Block>, Block::Hash), Option<(NumberFor<Block>, Block::Hash)>, Vec<u8>)>;
}
/// Blockchain info
#[derive(Debug)]
pub struct Info<Block: BlockT> {
/// Best block hash.
pub best_hash: Block::Hash,
/// Best block number.
pub best_number: <<Block as BlockT>::Header as HeaderT>::Number,
/// Genesis block hash.
pub genesis_hash: Block::Hash,
/// The head of the finalized chain.
pub finalized_hash: Block::Hash,
/// Last finalized block number.
pub finalized_number: <<Block as BlockT>::Header as HeaderT>::Number,
}
/// Block status.
#[derive(Debug, PartialEq, Eq)]
pub enum BlockStatus {
/// Already in the blockchain.
InChain,
/// Not in the queue or the blockchain.
Unknown,
}
/// A list of all well known keys in the blockchain cache.
pub mod well_known_cache_keys {
/// The type representing cache keys.
pub type Id = consensus::import_queue::CacheKeyId;
/// A list of authorities.
pub const AUTHORITIES: Id = *b"auth";
/// Current Epoch data.
pub const EPOCH: Id = *b"epch";
/// Changes trie configuration.
pub const CHANGES_TRIE_CONFIG: Id = *b"chtr";
}
+8 -8
View File
@@ -31,7 +31,7 @@ use hash_db::Hasher;
use primitives::{Blake2Hasher, NativeOrEncoded};
use sr_api::{ProofRecorder, InitializeBlock};
use crate::error;
use sp_blockchain;
/// Method call executor.
pub trait CallExecutor<B, H>
@@ -53,7 +53,7 @@ where
call_data: &[u8],
strategy: ExecutionStrategy,
extensions: Option<Extensions>,
) -> Result<Vec<u8>, error::Error>;
) -> Result<Vec<u8>, sp_blockchain::Error>;
/// Execute a contextual call on top of state in a block of a given hash.
///
@@ -62,7 +62,7 @@ where
/// of the execution context.
fn contextual_call<
'a,
IB: Fn() -> error::Result<()>,
IB: Fn() -> sp_blockchain::Result<()>,
EM: Fn(
Result<NativeOrEncoded<R>, Self::Error>,
Result<NativeOrEncoded<R>, Self::Error>
@@ -81,12 +81,12 @@ where
native_call: Option<NC>,
proof_recorder: &Option<ProofRecorder<B>>,
extensions: Option<Extensions>,
) -> error::Result<NativeOrEncoded<R>> where ExecutionManager<EM>: Clone;
) -> sp_blockchain::Result<NativeOrEncoded<R>> where ExecutionManager<EM>: Clone;
/// Extract RuntimeVersion of given block
///
/// No changes are made.
fn runtime_version(&self, id: &BlockId<B>) -> Result<RuntimeVersion, error::Error>;
fn runtime_version(&self, id: &BlockId<B>) -> Result<RuntimeVersion, sp_blockchain::Error>;
/// Execute a call to a contract on top of given state.
///
@@ -113,7 +113,7 @@ where
(S::Transaction, H::Out),
Option<ChangesTrieTransaction<Blake2Hasher, NumberFor<B>>>
),
error::Error,
sp_blockchain::Error,
>;
/// Execute a call to a contract on top of given state, gathering execution proof.
@@ -125,7 +125,7 @@ where
overlay: &mut OverlayedChanges,
method: &str,
call_data: &[u8]
) -> Result<(Vec<u8>, StorageProof), error::Error> {
) -> Result<(Vec<u8>, StorageProof), sp_blockchain::Error> {
let trie_state = state.as_trie_backend()
.ok_or_else(||
Box::new(state_machine::ExecutionError::UnableToGenerateProof)
@@ -143,7 +143,7 @@ where
overlay: &mut OverlayedChanges,
method: &str,
call_data: &[u8]
) -> Result<(Vec<u8>, StorageProof), error::Error>;
) -> Result<(Vec<u8>, StorageProof), sp_blockchain::Error>;
/// Get runtime version if supported.
fn native_runtime_version(&self) -> Option<&NativeVersion>;
+4 -4
View File
@@ -27,7 +27,7 @@ use consensus::BlockOrigin;
use crate::blockchain::Info;
use crate::notifications::StorageEventStream;
use crate::error;
use sp_blockchain;
/// Type that implements `futures::Stream` of block import events.
pub type ImportNotifications<Block> = mpsc::UnboundedReceiver<BlockImportNotification<Block>>;
@@ -63,7 +63,7 @@ pub trait BlockchainEvents<Block: BlockT> {
&self,
filter_keys: Option<&[StorageKey]>,
child_filter_keys: Option<&[(StorageKey, Option<Vec<StorageKey>>)]>,
) -> error::Result<StorageEventStream<Block::Hash>>;
) -> sp_blockchain::Result<StorageEventStream<Block::Hash>>;
}
/// Fetch block body by ID.
@@ -71,14 +71,14 @@ pub trait BlockBody<Block: BlockT> {
/// Get block body by ID. Returns `None` if the body is not stored.
fn block_body(&self,
id: &BlockId<Block>
) -> error::Result<Option<Vec<<Block as BlockT>::Extrinsic>>>;
) -> sp_blockchain::Result<Option<Vec<<Block as BlockT>::Extrinsic>>>;
}
/// Provide a list of potential uncle headers for a given block.
pub trait ProvideUncles<Block: BlockT> {
/// Gets the uncles of the block with `target_hash` going back `max_generation` ancestors.
fn uncles(&self, target_hash: Block::Hash, max_generation: NumberFor<Block>)
-> error::Result<Vec<Block::Header>>;
-> sp_blockchain::Result<Vec<Block::Header>>;
}
/// Client info
-155
View File
@@ -1,155 +0,0 @@
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Substrate client possible errors.
use std::{self, error, result};
use state_machine;
use sr_primitives::transaction_validity::TransactionValidityError;
use consensus;
use derive_more::{Display, From};
/// Client Result type alias
pub type Result<T> = result::Result<T, Error>;
/// 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)]
#[from(ignore)]
Backend(String),
/// Unknown block.
#[display(fmt = "UnknownBlock: {}", _0)]
#[from(ignore)]
UnknownBlock(String),
/// The `apply_extrinsic` is not valid due to the given `TransactionValidityError`.
#[display(fmt = "Extrinsic is not valid: {:?}", _0)]
ApplyExtrinsicFailed(TransactionValidityError),
/// Execution error.
#[display(fmt = "Execution: {}", _0)]
Execution(Box<dyn 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,
/// Error decoding header justification.
#[display(fmt = "error decoding justification for header")]
JustificationDecode,
/// Justification for header is correctly encoded, but invalid.
#[display(fmt = "bad justification for header: {}", _0)]
#[from(ignore)]
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, _1)]
CallResultDecode(&'static str, codec::Error),
/// Error converting a parameter between runtime and node.
#[display(fmt = "Error converting `{}` between runtime and node", _0)]
#[from(ignore)]
RuntimeParamConversion(String),
/// 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)]
#[from(ignore)]
ChangesTrieAccessFailed(String),
/// Last finalized block not parent of current.
#[display(fmt = "Did not finalize blocks in sequential order.")]
#[from(ignore)]
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")]
MissingHashRequiredForCHT,
/// Invalid calculated state root on block import.
#[display(fmt = "Calculated state root does not match.")]
InvalidStateRoot,
/// A convenience variant for String
#[display(fmt = "{}", _0)]
#[from(ignore)]
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 From<String> for Error {
fn from(s: String) -> Self {
Error::Msg(s)
}
}
impl<'a> From<&'a str> for Error {
fn from(s: &'a str) -> Self {
Error::Msg(s.into())
}
}
impl From<block_builder::ApplyExtrinsicFailed> for Error {
fn from(err: block_builder::ApplyExtrinsicFailed) -> Self {
use block_builder::ApplyExtrinsicFailed;
match err {
ApplyExtrinsicFailed::Validity(tx_validity) => Self::ApplyExtrinsicFailed(tx_validity),
ApplyExtrinsicFailed::Msg(msg) => Self::Msg(msg),
}
}
}
impl Error {
/// Chain a blockchain error.
pub fn from_blockchain(e: Box<Error>) -> Self {
Error::Blockchain(e)
}
/// Chain a state error.
pub fn from_state(e: Box<dyn state_machine::Error>) -> Self {
Error::Execution(e)
}
}
+6 -11
View File
@@ -18,20 +18,17 @@
#![warn(missing_docs)]
pub mod backend;
pub mod blockchain;
pub mod call_executor;
pub mod client;
pub mod error;
pub mod execution_extensions;
pub mod light;
pub mod notifications;
// TODO: avoid re-exports
pub use sp_blockchain as blockchain;
pub use backend::*;
pub use blockchain::*;
pub use notifications::*;
pub use call_executor::*;
pub use client::*;
pub use error::*;
pub use light::*;
pub use notifications::*;
@@ -40,9 +37,7 @@ pub use state_machine::{StorageProof, ExecutionStrategy};
/// Utility methods for the client.
pub mod utils {
use super::HeaderBackend;
use header_metadata::HeaderMetadata;
use crate::error;
use sp_blockchain::{HeaderBackend, HeaderMetadata, Error};
use primitives::H256;
use sr_primitives::traits::{Block as BlockT};
use std::borrow::Borrow;
@@ -56,8 +51,8 @@ pub mod utils {
pub fn is_descendent_of<'a, Block: BlockT<Hash=H256>, T, H: Borrow<H256> + 'a>(
client: &'a T,
current: Option<(H, H)>,
) -> impl Fn(&H256, &H256) -> Result<bool, error::Error> + 'a
where T: HeaderBackend<Block> + HeaderMetadata<Block, Error=error::Error>,
) -> impl Fn(&H256, &H256) -> Result<bool, Error> + 'a
where T: HeaderBackend<Block> + HeaderMetadata<Block, Error=Error>,
{
move |base, hash| {
if base == hash { return Ok(false); }
@@ -76,7 +71,7 @@ pub mod utils {
}
}
let ancestor = header_metadata::lowest_common_ancestor(client, *hash, *base)?;
let ancestor = sp_blockchain::lowest_common_ancestor(client, *hash, *base)?;
Ok(ancestor.hash == *base)
}
+5 -10
View File
@@ -28,16 +28,11 @@ use sr_primitives::{
};
use primitives::{ChangesTrieConfiguration};
use state_machine::StorageProof;
use header_metadata::HeaderMetadata;
use crate::{
backend::{
AuxStore, NewBlockState,
},
blockchain::{
well_known_cache_keys, HeaderBackend, Cache as BlockchainCache,
},
error::{ Error as ClientError, Result as ClientResult },
use sp_blockchain::{
HeaderMetadata, well_known_cache_keys, HeaderBackend, Cache as BlockchainCache,
Error as ClientError, Result as ClientResult,
};
use crate::backend::{ AuxStore, NewBlockState };
/// Remote call request.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct RemoteCallRequest<Header: HeaderT> {
@@ -288,7 +283,7 @@ pub trait RemoteBlockchain<Block: BlockT>: Send + Sync {
pub mod tests {
use futures::future::Ready;
use parking_lot::Mutex;
use crate::error::Error as ClientError;
use sp_blockchain::Error as ClientError;
use test_primitives::{Block, Header, Extrinsic};
use super::*;