Fix tons of warnings in newest nightly (#2784)

* Fix tons of warnings in newest nightly

* Fix sr-api-macro doc tests
This commit is contained in:
Bastian Köcher
2019-06-04 20:09:49 +02:00
committed by GitHub
parent 9700029203
commit 6142f95611
73 changed files with 359 additions and 316 deletions
@@ -56,7 +56,7 @@ pub trait AuthoringApi: Send + Sync + ProvideRuntimeApi where
/// Build a block on top of the given block, with inherent extrinsics and
/// inherent digests pre-pushed.
fn build_block<F: FnMut(&mut BlockBuilder<Self::Block>) -> ()>(
fn build_block<F: FnMut(&mut dyn BlockBuilder<Self::Block>) -> ()>(
&self,
at: &BlockId<Self::Block>,
inherent_data: InherentData,
@@ -91,7 +91,7 @@ impl<B, E, Block, RA> AuthoringApi for SubstrateClient<B, E, Block, RA> where
type Block = Block;
type Error = client::error::Error;
fn build_block<F: FnMut(&mut BlockBuilder<Self::Block>) -> ()>(
fn build_block<F: FnMut(&mut dyn BlockBuilder<Self::Block>) -> ()>(
&self,
at: &BlockId<Self::Block>,
inherent_data: InherentData,
@@ -162,7 +162,7 @@ pub struct Proposer<Block: BlockT, C, A: txpool::ChainApi> {
parent_id: BlockId<Block>,
parent_number: <<Block as BlockT>::Header as HeaderT>::Number,
transaction_pool: Arc<TransactionPool<A>>,
now: Box<Fn() -> time::Instant>,
now: Box<dyn Fn() -> time::Instant>,
}
impl<Block, C, A> consensus_common::Proposer<<C as AuthoringApi>::Block> for Proposer<Block, C, A> where
+2 -2
View File
@@ -617,7 +617,7 @@ where
let to = cli.to;
let json = cli.json;
let file: Box<Write> = match cli.output {
let file: Box<dyn Write> = match cli.output {
Some(filename) => Box::new(File::create(filename)?),
None => Box::new(stdout()),
};
@@ -640,7 +640,7 @@ where
{
let config = create_config_with_db_path::<F, _>(spec_factory, &cli.shared_params, version)?;
let file: Box<Read> = match cli.input {
let file: Box<dyn Read> = match cli.input {
Some(filename) => Box::new(File::open(filename)?),
None => Box::new(stdin()),
};
+2 -2
View File
@@ -476,7 +476,7 @@ impl Keyring {
}
/// Default to verbosity level 0, if none is provided.
fn parse_telemetry_endpoints(s: &str) -> Result<(String, u8), Box<std::error::Error>> {
fn parse_telemetry_endpoints(s: &str) -> Result<(String, u8), Box<dyn std::error::Error>> {
let pos = s.find(' ');
match pos {
None => {
@@ -512,7 +512,7 @@ impl From<Cors> for Option<Vec<String>> {
}
/// Parse cors origins
fn parse_cors(s: &str) -> Result<Cors, Box<std::error::Error>> {
fn parse_cors(s: &str) -> Result<Cors, Box<dyn std::error::Error>> {
let mut is_all = false;
let mut origins = Vec::new();
for part in s.split(',') {
+3 -3
View File
@@ -97,19 +97,19 @@ pub struct DbColumns {
pub struct DbStorage {
name: Vec<u8>,
meta_key: Vec<u8>,
db: Arc<KeyValueDB>,
db: Arc<dyn KeyValueDB>,
columns: DbColumns,
}
impl DbStorage {
/// Create new database-backed list cache storage.
pub fn new(name: Vec<u8>, db: Arc<KeyValueDB>, columns: DbColumns) -> Self {
pub fn new(name: Vec<u8>, db: Arc<dyn KeyValueDB>, columns: DbColumns) -> Self {
let meta_key = meta::key(&name);
DbStorage { name, meta_key, db, columns }
}
/// Get reference to the database.
pub fn db(&self) -> &Arc<KeyValueDB> { &self.db }
pub fn db(&self) -> &Arc<dyn KeyValueDB> { &self.db }
/// Get reference to the database columns.
pub fn columns(&self) -> &DbColumns { &self.columns }
+3 -3
View File
@@ -77,7 +77,7 @@ impl<T> CacheItemT for T where T: Clone + Decode + Encode + PartialEq {}
/// Database-backed blockchain data cache.
pub struct DbCache<Block: BlockT> {
cache_at: HashMap<CacheKeyId, ListCache<Block, Vec<u8>, self::list_storage::DbStorage>>,
db: Arc<KeyValueDB>,
db: Arc<dyn KeyValueDB>,
key_lookup_column: Option<u32>,
header_column: Option<u32>,
authorities_column: Option<u32>,
@@ -88,7 +88,7 @@ pub struct DbCache<Block: BlockT> {
impl<Block: BlockT> DbCache<Block> {
/// Create new cache.
pub fn new(
db: Arc<KeyValueDB>,
db: Arc<dyn KeyValueDB>,
key_lookup_column: Option<u32>,
header_column: Option<u32>,
authorities_column: Option<u32>,
@@ -150,7 +150,7 @@ impl<Block: BlockT> DbCache<Block> {
fn get_cache_helper<'a, Block: BlockT>(
cache_at: &'a mut HashMap<CacheKeyId, ListCache<Block, Vec<u8>, self::list_storage::DbStorage>>,
name: CacheKeyId,
db: &Arc<KeyValueDB>,
db: &Arc<dyn KeyValueDB>,
key_lookup: Option<u32>,
header: Option<u32>,
cache: Option<u32>,
+14 -9
View File
@@ -70,7 +70,7 @@ const CANONICALIZATION_DELAY: u64 = 4096;
const MIN_BLOCKS_TO_KEEP_CHANGES_TRIES_FOR: u32 = 32768;
/// DB-backed patricia trie state, transaction type is an overlay of changes to commit.
pub type DbState = state_machine::TrieBackend<Arc<state_machine::Storage<Blake2Hasher>>, Blake2Hasher>;
pub type DbState = state_machine::TrieBackend<Arc<dyn state_machine::Storage<Blake2Hasher>>, Blake2Hasher>;
pub struct RefTrackingState<Block: BlockT> {
state: DbState,
@@ -213,7 +213,7 @@ struct PendingBlock<Block: BlockT> {
}
// wrapper that implements trait required for state_db
struct StateMetaDb<'a>(&'a KeyValueDB);
struct StateMetaDb<'a>(&'a dyn KeyValueDB);
impl<'a> state_db::MetaDb for StateMetaDb<'a> {
type Error = io::Error;
@@ -225,13 +225,13 @@ impl<'a> state_db::MetaDb for StateMetaDb<'a> {
/// Block database
pub struct BlockchainDb<Block: BlockT> {
db: Arc<KeyValueDB>,
db: Arc<dyn KeyValueDB>,
meta: Arc<RwLock<Meta<NumberFor<Block>, Block::Hash>>>,
leaves: RwLock<LeafSet<Block::Hash, NumberFor<Block>>>,
}
impl<Block: BlockT> BlockchainDb<Block> {
fn new(db: Arc<KeyValueDB>) -> Result<Self, client::error::Error> {
fn new(db: Arc<dyn KeyValueDB>) -> Result<Self, client::error::Error> {
let meta = read_meta::<Block>(&*db, columns::META, columns::HEADER)?;
let leaves = LeafSet::read_from_db(&*db, columns::META, meta_keys::LEAF_PREFIX)?;
Ok(BlockchainDb {
@@ -340,7 +340,7 @@ impl<Block: BlockT> client::blockchain::Backend<Block> for BlockchainDb<Block> {
Ok(self.meta.read().finalized_hash.clone())
}
fn cache(&self) -> Option<Arc<client::blockchain::Cache<Block>>> {
fn cache(&self) -> Option<Arc<dyn client::blockchain::Cache<Block>>> {
None
}
@@ -354,7 +354,7 @@ impl<Block: BlockT> client::blockchain::Backend<Block> for BlockchainDb<Block> {
}
impl<Block: BlockT> client::blockchain::ProvideCache<Block> for BlockchainDb<Block> {
fn cache(&self) -> Option<Arc<client::blockchain::Cache<Block>>> {
fn cache(&self) -> Option<Arc<dyn client::blockchain::Cache<Block>>> {
None
}
}
@@ -473,7 +473,7 @@ where Block: BlockT<Hash=H256>,
}
struct StorageDb<Block: BlockT> {
pub db: Arc<KeyValueDB>,
pub db: Arc<dyn KeyValueDB>,
pub state_db: StateDb<Block::Hash, Vec<u8>>,
}
@@ -512,7 +512,7 @@ impl state_machine::Storage<Blake2Hasher> for DbGenesisStorage {
}
pub struct DbChangesTrieStorage<Block: BlockT> {
db: Arc<KeyValueDB>,
db: Arc<dyn KeyValueDB>,
meta: Arc<RwLock<Meta<NumberFor<Block>, Block::Hash>>>,
min_blocks_to_keep: Option<u32>,
_phantom: ::std::marker::PhantomData<Block>,
@@ -693,7 +693,12 @@ impl<Block: BlockT<Hash=H256>> Backend<Block> {
).expect("failed to create test-db")
}
fn from_kvdb(db: Arc<KeyValueDB>, pruning: PruningMode, canonicalization_delay: u64, state_cache_size: usize) -> Result<Self, client::error::Error> {
fn from_kvdb(
db: Arc<dyn KeyValueDB>,
pruning: PruningMode,
canonicalization_delay: u64,
state_cache_size: usize
) -> Result<Self, client::error::Error> {
let is_archive_pruning = pruning.is_archive();
let blockchain = BlockchainDb::new(db.clone())?;
let meta = blockchain.meta.clone();
+4 -4
View File
@@ -59,7 +59,7 @@ const CHANGES_TRIE_CHT_PREFIX: u8 = 1;
/// Light blockchain storage. Stores most recent headers + CHTs for older headers.
/// Locks order: meta, leaves, cache.
pub struct LightStorage<Block: BlockT> {
db: Arc<KeyValueDB>,
db: Arc<dyn KeyValueDB>,
meta: RwLock<Meta<NumberFor<Block>, Block::Hash>>,
leaves: RwLock<LeafSet<Block::Hash, NumberFor<Block>>>,
cache: Arc<DbCacheSync<Block>>,
@@ -96,7 +96,7 @@ impl<Block> LightStorage<Block>
Self::from_kvdb(db as Arc<_>).expect("failed to create test-db")
}
fn from_kvdb(db: Arc<KeyValueDB>) -> ClientResult<Self> {
fn from_kvdb(db: Arc<dyn KeyValueDB>) -> ClientResult<Self> {
let meta = read_meta::<Block>(&*db, columns::META, columns::HEADER)?;
let leaves = LeafSet::read_from_db(&*db, columns::META, meta_keys::LEAF_PREFIX)?;
let cache = DbCache::new(
@@ -557,7 +557,7 @@ impl<Block> LightBlockchainStorage<Block> for LightStorage<Block>
Ok(self.meta.read().finalized_hash.clone())
}
fn cache(&self) -> Option<Arc<BlockchainCache<Block>>> {
fn cache(&self) -> Option<Arc<dyn BlockchainCache<Block>>> {
Some(self.cache.clone())
}
}
@@ -888,7 +888,7 @@ pub(crate) mod tests {
map
}
fn get_authorities(cache: &BlockchainCache<Block>, at: BlockId<Block>) -> Option<Vec<AuthorityId>> {
fn get_authorities(cache: &dyn BlockchainCache<Block>, at: BlockId<Block>) -> Option<Vec<AuthorityId>> {
cache.get_at(&well_known_cache_keys::AUTHORITIES, &at).and_then(|val| Decode::decode(&mut &val[..]))
}
+16 -9
View File
@@ -17,9 +17,7 @@
//! Db-based backend utility structures and functions, used by both
//! full and light storages.
use std::sync::Arc;
use std::io;
use std::convert::TryInto;
use std::{io, convert::TryInto, sync::Arc};
use kvdb::{KeyValueDB, DBTransaction};
#[cfg(feature = "kvdb-rocksdb")]
@@ -171,7 +169,7 @@ pub fn insert_hash_to_key_mapping<N: TryInto<u32>, H: AsRef<[u8]> + Clone>(
/// block lookup key is the DB-key header, block and justification are stored under.
/// looks up lookup key by hash from DB as necessary.
pub fn block_id_to_lookup_key<Block>(
db: &KeyValueDB,
db: &dyn KeyValueDB,
key_lookup_col: Option<u32>,
id: BlockId<Block>
) -> Result<Option<Vec<u8>>, client::error::Error> where
@@ -197,7 +195,11 @@ pub fn db_err(err: io::Error) -> client::error::Error {
/// Open RocksDB database.
#[cfg(feature = "kvdb-rocksdb")]
pub fn open_database(config: &DatabaseSettings, col_meta: Option<u32>, db_type: &str) -> client::error::Result<Arc<KeyValueDB>> {
pub fn open_database(
config: &DatabaseSettings,
col_meta: Option<u32>,
db_type: &str
) -> client::error::Result<Arc<dyn 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::Error::Backend("Invalid database path".into()))?;
@@ -222,7 +224,12 @@ pub fn open_database(config: &DatabaseSettings, col_meta: Option<u32>, db_type:
}
/// Read database column entry for the given block.
pub fn read_db<Block>(db: &KeyValueDB, col_index: Option<u32>, col: Option<u32>, id: BlockId<Block>) -> client::error::Result<Option<DBValue>>
pub fn read_db<Block>(
db: &dyn KeyValueDB,
col_index: Option<u32>,
col: Option<u32>,
id: BlockId<Block>
) -> client::error::Result<Option<DBValue>>
where
Block: BlockT,
{
@@ -234,7 +241,7 @@ pub fn read_db<Block>(db: &KeyValueDB, col_index: Option<u32>, col: Option<u32>,
/// Read a header from the database.
pub fn read_header<Block: BlockT>(
db: &KeyValueDB,
db: &dyn KeyValueDB,
col_index: Option<u32>,
col: Option<u32>,
id: BlockId<Block>,
@@ -252,7 +259,7 @@ pub fn read_header<Block: BlockT>(
/// Required header from the database.
pub fn require_header<Block: BlockT>(
db: &KeyValueDB,
db: &dyn KeyValueDB,
col_index: Option<u32>,
col: Option<u32>,
id: BlockId<Block>,
@@ -262,7 +269,7 @@ pub fn require_header<Block: BlockT>(
}
/// Read meta from the database.
pub fn read_meta<Block>(db: &KeyValueDB, col_meta: Option<u32>, col_header: Option<u32>) -> Result<
pub fn read_meta<Block>(db: &dyn KeyValueDB, col_meta: Option<u32>, col_header: Option<u32>) -> Result<
Meta<<<Block as BlockT>::Header as HeaderT>::Number, Block::Hash>,
client::error::Error,
>
+2 -2
View File
@@ -81,7 +81,7 @@ pub trait Backend<Block: BlockT>: HeaderBackend<Block> {
/// 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<Cache<Block>>>;
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.
@@ -95,7 +95,7 @@ pub trait Backend<Block: BlockT>: HeaderBackend<Block> {
/// 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<Cache<Block>>>;
fn cache(&self) -> Option<Arc<dyn Cache<Block>>>;
}
/// Blockchain optional data cache.
+2 -2
View File
@@ -125,7 +125,7 @@ where
let trie_state = state.as_trie_backend()
.ok_or_else(||
Box::new(state_machine::ExecutionError::UnableToGenerateProof)
as Box<state_machine::Error>
as Box<dyn state_machine::Error>
)?;
self.prove_at_trie_state(trie_state, overlay, method, call_data)
}
@@ -246,7 +246,7 @@ where
let trie_state = state.as_trie_backend()
.ok_or_else(||
Box::new(state_machine::ExecutionError::UnableToGenerateProof)
as Box<state_machine::Error>
as Box<dyn state_machine::Error>
)?;
let backend = state_machine::ProvingBackend::new_with_recorder(
+2 -2
View File
@@ -26,7 +26,7 @@ use std::hash::Hash;
pub fn read_children<
K: Eq + Hash + Clone + Encode + Decode,
V: Eq + Hash + Clone + Encode + Decode,
>(db: &KeyValueDB, column: Option<u32>, prefix: &[u8], parent_hash: K) -> error::Result<Vec<V>> {
>(db: &dyn KeyValueDB, column: Option<u32>, prefix: &[u8], parent_hash: K) -> error::Result<Vec<V>> {
let mut buf = prefix.to_vec();
parent_hash.using_encoded(|s| buf.extend(s));
@@ -116,6 +116,6 @@ mod tests {
let r2: Vec<u32> = read_children(&db, None, PREFIX, 1_2).unwrap();
assert_eq!(r1, vec![1_3, 1_5]);
assert_eq!(r2.len(), 0);
assert_eq!(r2.len(), 0);
}
}
+7 -7
View File
@@ -564,7 +564,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
cht_size: NumberFor<Block>,
) -> error::Result<ChangesProof<Block::Header>> {
struct AccessedRootsRecorder<'a, Block: BlockT> {
storage: &'a ChangesTrieStorage<Blake2Hasher, NumberFor<Block>>,
storage: &'a dyn ChangesTrieStorage<Blake2Hasher, NumberFor<Block>>,
min: NumberFor<Block>,
required_roots_proofs: Mutex<BTreeMap<NumberFor<Block>, H256>>,
};
@@ -695,7 +695,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
/// Create a new block, built on the head of the chain.
pub fn new_block(
&self,
&self,
inherent_digests: DigestFor<Block>,
) -> error::Result<block_builder::BlockBuilder<Block, Self>> where
E: Clone + Send + Sync,
@@ -708,8 +708,8 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
/// Create a new block, built on top of `parent`.
pub fn new_block_at(
&self,
parent: &BlockId<Block>,
&self,
parent: &BlockId<Block>,
inherent_digests: DigestFor<Block>,
) -> error::Result<block_builder::BlockBuilder<Block, Self>> where
E: Clone + Send + Sync,
@@ -726,8 +726,8 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
/// These recorded trie nodes can be used by a third party to proof the
/// output of this block builder without having access to the full storage.
pub fn new_block_at_with_proof_recording(
&self,
parent: &BlockId<Block>,
&self,
parent: &BlockId<Block>,
inherent_digests: DigestFor<Block>,
) -> error::Result<block_builder::BlockBuilder<Block, Self>> where
E: Clone + Send + Sync,
@@ -1319,7 +1319,7 @@ impl<B, E, Block, RA> ProvideCache<Block> for Client<B, E, Block, RA> where
B: backend::Backend<Block, Blake2Hasher>,
Block: BlockT<Hash=H256>,
{
fn cache(&self) -> Option<Arc<Cache<Block>>> {
fn cache(&self) -> Option<Arc<dyn Cache<Block>>> {
self.backend.blockchain().cache()
}
}
+3 -3
View File
@@ -42,7 +42,7 @@ pub enum Error {
ApplyExtrinsicFailed(ApplyError),
/// Execution error.
#[display(fmt = "Execution: {}", _0)]
Execution(Box<state_machine::Error>),
Execution(Box<dyn state_machine::Error>),
/// Blockchain error.
#[display(fmt = "Blockchain: {}", _0)]
Blockchain(Box<Error>),
@@ -100,7 +100,7 @@ pub enum Error {
}
impl error::Error for Error {
fn source(&self) -> Option<&(error::Error + 'static)> {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Error::Consensus(e) => Some(e),
Error::Blockchain(e) => Some(e),
@@ -128,7 +128,7 @@ impl Error {
}
/// Chain a state error.
pub fn from_state(e: Box<state_machine::Error + Send>) -> Self {
pub fn from_state(e: Box<dyn state_machine::Error + Send>) -> Self {
Error::Execution(e)
}
}
+3 -3
View File
@@ -343,7 +343,7 @@ impl<Block: BlockT> blockchain::Backend<Block> for Blockchain<Block> {
Ok(self.storage.read().finalized_hash.clone())
}
fn cache(&self) -> Option<Arc<blockchain::Cache<Block>>> {
fn cache(&self) -> Option<Arc<dyn blockchain::Cache<Block>>> {
None
}
@@ -357,7 +357,7 @@ impl<Block: BlockT> blockchain::Backend<Block> for Blockchain<Block> {
}
impl<Block: BlockT> blockchain::ProvideCache<Block> for Blockchain<Block> {
fn cache(&self) -> Option<Arc<blockchain::Cache<Block>>> {
fn cache(&self) -> Option<Arc<dyn blockchain::Cache<Block>>> {
None
}
}
@@ -433,7 +433,7 @@ impl<Block: BlockT> light::blockchain::Storage<Block> for Blockchain<Block>
.ok_or_else(|| error::Error::Backend(format!("Changes trie CHT for block {} not exists", block)))
}
fn cache(&self) -> Option<Arc<blockchain::Cache<Block>>> {
fn cache(&self) -> Option<Arc<dyn blockchain::Cache<Block>>> {
None
}
}
+1 -1
View File
@@ -77,7 +77,7 @@ impl<H, N> LeafSet<H, N> where
}
/// Read the leaf list from the DB, using given prefix for keys.
pub fn read_from_db(db: &KeyValueDB, column: Option<u32>, prefix: &[u8]) -> error::Result<Self> {
pub fn read_from_db(db: &dyn KeyValueDB, column: Option<u32>, prefix: &[u8]) -> error::Result<Self> {
let mut storage = BTreeMap::new();
for (key, value) in db.iter_from_prefix(column, prefix) {
@@ -70,7 +70,7 @@ pub trait Storage<Block: BlockT>: AuxStore + BlockchainHeaderBackend<Block> {
) -> ClientResult<Block::Hash>;
/// Get storage cache.
fn cache(&self) -> Option<Arc<BlockchainCache<Block>>>;
fn cache(&self) -> Option<Arc<dyn BlockchainCache<Block>>>;
}
/// Light client blockchain.
@@ -175,7 +175,7 @@ impl<S, F, Block> BlockchainBackend<Block> for Blockchain<S, F> where Block: Blo
self.storage.last_finalized()
}
fn cache(&self) -> Option<Arc<BlockchainCache<Block>>> {
fn cache(&self) -> Option<Arc<dyn BlockchainCache<Block>>> {
self.storage.cache()
}
@@ -189,7 +189,7 @@ impl<S, F, Block> BlockchainBackend<Block> for Blockchain<S, F> where Block: Blo
}
impl<S: Storage<Block>, F, Block: BlockT> ProvideCache<Block> for Blockchain<S, F> {
fn cache(&self) -> Option<Arc<BlockchainCache<Block>>> {
fn cache(&self) -> Option<Arc<dyn BlockchainCache<Block>>> {
self.storage.cache()
}
}
@@ -303,7 +303,7 @@ pub mod tests {
).into())
}
fn cache(&self) -> Option<Arc<BlockchainCache<Block>>> {
fn cache(&self) -> Option<Arc<dyn BlockchainCache<Block>>> {
None
}
}
@@ -400,7 +400,7 @@ pub fn prove_execution<Block, S, E>(
E: CallExecutor<Block, Blake2Hasher>,
{
let trie_state = state.as_trie_backend()
.ok_or_else(|| Box::new(state_machine::ExecutionError::UnableToGenerateProof) as Box<state_machine::Error>)?;
.ok_or_else(|| Box::new(state_machine::ExecutionError::UnableToGenerateProof) as Box<dyn state_machine::Error>)?;
// prepare execution environment + record preparation proof
let mut changes = Default::default();
+6 -6
View File
@@ -620,7 +620,7 @@ pub mod tests {
#[test]
fn storage_read_proof_is_generated_and_checked() {
let (local_checker, remote_block_header, remote_read_proof, authorities_len) = prepare_for_read_proof_check();
assert_eq!((&local_checker as &FetchChecker<Block>).check_read_proof(&RemoteReadRequest::<Header> {
assert_eq!((&local_checker as &dyn FetchChecker<Block>).check_read_proof(&RemoteReadRequest::<Header> {
block: remote_block_header.hash(),
header: remote_block_header,
key: well_known_keys::AUTHORITY_COUNT.to_vec(),
@@ -631,7 +631,7 @@ pub mod tests {
#[test]
fn header_proof_is_generated_and_checked() {
let (local_checker, local_cht_root, remote_block_header, remote_header_proof) = prepare_for_header_proof_check(true);
assert_eq!((&local_checker as &FetchChecker<Block>).check_header_proof(&RemoteHeaderRequest::<Header> {
assert_eq!((&local_checker as &dyn FetchChecker<Block>).check_header_proof(&RemoteHeaderRequest::<Header> {
cht_root: local_cht_root,
block: 1,
retry_count: None,
@@ -642,7 +642,7 @@ pub mod tests {
fn check_header_proof_fails_if_cht_root_is_invalid() {
let (local_checker, _, mut remote_block_header, remote_header_proof) = prepare_for_header_proof_check(true);
remote_block_header.number = 100;
assert!((&local_checker as &FetchChecker<Block>).check_header_proof(&RemoteHeaderRequest::<Header> {
assert!((&local_checker as &dyn FetchChecker<Block>).check_header_proof(&RemoteHeaderRequest::<Header> {
cht_root: Default::default(),
block: 1,
retry_count: None,
@@ -653,7 +653,7 @@ pub mod tests {
fn check_header_proof_fails_if_invalid_header_provided() {
let (local_checker, local_cht_root, mut remote_block_header, remote_header_proof) = prepare_for_header_proof_check(true);
remote_block_header.number = 100;
assert!((&local_checker as &FetchChecker<Block>).check_header_proof(&RemoteHeaderRequest::<Header> {
assert!((&local_checker as &dyn FetchChecker<Block>).check_header_proof(&RemoteHeaderRequest::<Header> {
cht_root: local_cht_root,
block: 1,
retry_count: None,
@@ -667,7 +667,7 @@ pub mod tests {
Arc::new(DummyBlockchain::new(DummyStorage::new())),
test_client::LocalExecutor::new(None)
);
let local_checker = &local_checker as &FetchChecker<Block>;
let local_checker = &local_checker as &dyn FetchChecker<Block>;
let max = remote_client.info().chain.best_number;
let max_hash = remote_client.info().chain.best_hash;
@@ -763,7 +763,7 @@ pub mod tests {
Arc::new(DummyBlockchain::new(DummyStorage::new())),
test_client::LocalExecutor::new(None)
);
let local_checker = &local_checker as &FetchChecker<Block>;
let local_checker = &local_checker as &dyn FetchChecker<Block>;
let max = remote_client.info().chain.best_number;
let max_hash = remote_client.info().chain.best_hash;
+3 -3
View File
@@ -206,7 +206,7 @@ impl<H, B, C, E, I, P, Error, SO> SlotWorker<B> for AuraWorker<C, E, I, P, SO> w
DigestItemFor<B>: CompatibleDigestItem<P> + DigestItem<AuthorityId=AuthorityId<P>, Hash=B::Hash>,
Error: ::std::error::Error + Send + From<::consensus_common::Error> + From<I::Error> + 'static,
{
type OnSlot = Box<Future<Item=(), Error=consensus_common::Error> + Send>;
type OnSlot = Box<dyn Future<Item=(), Error=consensus_common::Error> + Send>;
fn on_start(
&self,
@@ -578,7 +578,7 @@ impl<B: Block, C, E, P> Verifier<B> for AuraVerifier<C, E, P> where
// skip the inherents verification if the runtime API is old.
if self.client
.runtime_api()
.has_api_with::<BlockBuilderApi<B>, _>(&BlockId::Hash(parent_hash), |v| v >= 2)
.has_api_with::<dyn BlockBuilderApi<B>, _>(&BlockId::Hash(parent_hash), |v| v >= 2)
.map_err(|e| format!("{:?}", e))?
{
self.check_inherents(
@@ -681,7 +681,7 @@ fn authorities<B, C>(client: &C, at: &BlockId<B>) -> Result<Vec<AuthorityIdFor<B
.and_then(|cache| cache.get_at(&well_known_cache_keys::AUTHORITIES, at)
.and_then(|v| Decode::decode(&mut &v[..])))
.or_else(|| {
if client.runtime_api().has_api::<AuthoritiesApi<B>>(at).unwrap_or(false) {
if client.runtime_api().has_api::<dyn AuthoritiesApi<B>>(at).unwrap_or(false) {
AuthoritiesApi::authorities(&*client.runtime_api(), at).ok()
} else {
CoreApi::authorities(&*client.runtime_api(), at).ok()
+2 -2
View File
@@ -251,7 +251,7 @@ impl<Hash, H, B, C, E, I, Error, SO> SlotWorker<B> for BabeWorker<C, E, I, SO> w
SO: SyncOracle + Send + Clone,
Error: std::error::Error + Send + From<::consensus_common::Error> + From<I::Error> + 'static,
{
type OnSlot = Box<Future<Item=(), Error=consensus_common::Error> + Send>;
type OnSlot = Box<dyn Future<Item=(), Error=consensus_common::Error> + Send>;
fn on_start(
&self,
@@ -715,7 +715,7 @@ fn authorities<B, C>(client: &C, at: &BlockId<B>) -> Result<
.and_then(|cache| cache.get_at(&well_known_cache_keys::AUTHORITIES, at)
.and_then(|v| Decode::decode(&mut &v[..])))
.or_else(|| {
if client.runtime_api().has_api::<AuthoritiesApi<B>>(at).unwrap_or(false) {
if client.runtime_api().has_api::<dyn AuthoritiesApi<B>>(at).unwrap_or(false) {
AuthoritiesApi::authorities(&*client.runtime_api(), at).ok()
} else {
panic!("We dont support deprecated code with new consensus algorithms, \
@@ -197,7 +197,7 @@ pub trait JustificationImport<B: BlockT> {
type Error: ::std::error::Error + Send + 'static;
/// Called by the import queue when it is started.
fn on_start(&self, _link: &crate::import_queue::Link<B>) { }
fn on_start(&self, _link: &dyn crate::import_queue::Link<B>) { }
/// Import a Block justification and finalize the given block.
fn import_justification(
@@ -210,10 +210,10 @@ pub trait JustificationImport<B: BlockT> {
/// Finality proof import trait.
pub trait FinalityProofImport<B: BlockT> {
type Error: ::std::error::Error + Send + 'static;
type Error: std::error::Error + Send + 'static;
/// Called by the import queue when it is started.
fn on_start(&self, _link: &crate::import_queue::Link<B>) { }
fn on_start(&self, _link: &dyn crate::import_queue::Link<B>) { }
/// Import a Block justification and finalize the given block. Returns finalized block or error.
fn import_finality_proof(
@@ -221,7 +221,7 @@ pub trait FinalityProofImport<B: BlockT> {
hash: B::Hash,
number: NumberFor<B>,
finality_proof: Vec<u8>,
verifier: &Verifier<B>,
verifier: &dyn Verifier<B>,
) -> Result<(B::Hash, NumberFor<B>), Self::Error>;
}
+1 -1
View File
@@ -64,7 +64,7 @@ pub enum Error {
InvalidJustification,
/// Some other error.
#[display(fmt="Other error: {}", _0)]
Other(Box<error::Error + Send>),
Other(Box<dyn error::Error + Send>),
/// Error from the client while importing
#[display(fmt="Import failed: {}", _0)]
ClientImport(String),
@@ -103,7 +103,7 @@ pub trait ImportQueue<B: BlockT>: Send + Sync {
///
/// This is called automatically by the network service when synchronization
/// begins.
fn start(&self, _link: Box<Link<B>>) -> Result<(), std::io::Error> {
fn start(&self, _link: Box<dyn Link<B>>) -> Result<(), std::io::Error> {
Ok(())
}
/// Import bunch of blocks.
@@ -120,7 +120,7 @@ pub struct BasicSyncQueue<B: BlockT, V: Verifier<B>> {
}
struct BasicSyncQueueData<B: BlockT, V: Verifier<B>> {
link: Mutex<Option<Box<Link<B>>>>,
link: Mutex<Option<Box<dyn Link<B>>>>,
block_import: SharedBlockImport<B>,
verifier: Arc<V>,
justification_import: Option<SharedJustificationImport<B>>,
@@ -147,7 +147,7 @@ impl<B: BlockT, V: Verifier<B>> BasicSyncQueue<B, V> {
}
impl<B: BlockT, V: 'static + Verifier<B>> ImportQueue<B> for BasicSyncQueue<B, V> {
fn start(&self, link: Box<Link<B>>) -> Result<(), std::io::Error> {
fn start(&self, link: Box<dyn Link<B>>) -> Result<(), std::io::Error> {
if let Some(justification_import) = self.data.justification_import.as_ref() {
justification_import.on_start(&*link);
}
@@ -287,7 +287,7 @@ impl<B: BlockT> BasicQueue<B> {
}
impl<B: BlockT> ImportQueue<B> for BasicQueue<B> {
fn start(&self, link: Box<Link<B>>) -> Result<(), std::io::Error> {
fn start(&self, link: Box<dyn Link<B>>) -> Result<(), std::io::Error> {
let connect_err = || Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Failed to connect import queue threads",
@@ -328,7 +328,7 @@ pub enum BlockImportMsg<B: BlockT> {
ImportBlocks(BlockOrigin, Vec<IncomingBlock<B>>),
ImportJustification(Origin, B::Hash, NumberFor<B>, Justification),
ImportFinalityProof(Origin, B::Hash, NumberFor<B>, Vec<u8>),
Start(Box<Link<B>>, Sender<Result<(), std::io::Error>>),
Start(Box<dyn Link<B>>, Sender<Result<(), std::io::Error>>),
Shutdown(Sender<()>),
#[cfg(any(test, feature = "test-helpers"))]
Synchronize,
@@ -360,7 +360,7 @@ struct BlockImporter<B: BlockT> {
result_port: Receiver<BlockImportWorkerMsg<B>>,
worker_sender: Option<Sender<BlockImportWorkerMsg<B>>>,
link: Option<Box<dyn Link<B>>>,
verifier: Arc<Verifier<B>>,
verifier: Arc<dyn Verifier<B>>,
justification_import: Option<SharedJustificationImport<B>>,
finality_proof_import: Option<SharedFinalityProofImport<B>>,
finality_proof_request_builder: Option<SharedFinalityProofRequestBuilder<B>>,
@@ -370,7 +370,7 @@ impl<B: BlockT> BlockImporter<B> {
fn new(
result_port: Receiver<BlockImportWorkerMsg<B>>,
worker_sender: Sender<BlockImportWorkerMsg<B>>,
verifier: Arc<Verifier<B>>,
verifier: Arc<dyn Verifier<B>>,
justification_import: Option<SharedJustificationImport<B>>,
finality_proof_import: Option<SharedFinalityProofImport<B>>,
finality_proof_request_builder: Option<SharedFinalityProofRequestBuilder<B>>,
@@ -667,7 +667,7 @@ pub enum BlockImportError {
/// Imports single notification and send notification to the link (if provided).
fn import_single_justification<B: BlockT>(
link: &Option<Box<Link<B>>>,
link: &Option<Box<dyn Link<B>>>,
justification_import: &Option<SharedJustificationImport<B>>,
who: Origin,
hash: B::Hash,
@@ -723,7 +723,7 @@ fn import_single_finality_proof<B: BlockT, V: Verifier<B>>(
/// Process result of block(s) import.
fn process_import_results<B: BlockT>(
link: &Link<B>,
link: &dyn Link<B>,
results: Vec<(
Result<BlockImportResult<NumberFor<B>>, BlockImportError>,
B::Hash,
@@ -801,7 +801,7 @@ fn process_import_results<B: BlockT>(
/// Import several blocks at once, returning import result for each block.
fn import_many_blocks<B: BlockT, V: Verifier<B>>(
import_handle: &BlockImport<B, Error = ConsensusError>,
import_handle: &dyn BlockImport<B, Error = ConsensusError>,
blocks_origin: BlockOrigin,
blocks: Vec<IncomingBlock<B>>,
verifier: Arc<V>,
@@ -854,7 +854,7 @@ fn import_many_blocks<B: BlockT, V: Verifier<B>>(
/// Single block import function.
pub fn import_single_block<B: BlockT, V: Verifier<B>>(
import_handle: &BlockImport<B, Error = ConsensusError>,
import_handle: &dyn BlockImport<B, Error = ConsensusError>,
block_origin: BlockOrigin,
block: IncomingBlock<B>,
verifier: Arc<V>,
@@ -107,7 +107,7 @@ fn safe_call<F, U>(f: F) -> Result<U>
/// Set up the externalities and safe calling environment to execute calls to a native runtime.
///
/// If the inner closure panics, it will be caught and return an error.
pub fn with_native_environment<F, U>(ext: &mut Externalities<Blake2Hasher>, f: F) -> Result<U>
pub fn with_native_environment<F, U>(ext: &mut dyn Externalities<Blake2Hasher>, f: F) -> Result<U>
where F: UnwindSafe + FnOnce() -> U
{
::runtime_io::with_externalities(ext, move || safe_call(f))
@@ -121,7 +121,7 @@ pub trait NativeExecutionDispatch: Send + Sync {
/// Dispatch a method and input data to be executed natively. Returns `Some` result or `None`
/// if the `method` is unknown. Panics if there's an unrecoverable error.
// fn dispatch<H: hash_db::Hasher>(ext: &mut Externalities<H>, method: &str, data: &[u8]) -> Result<Vec<u8>>;
fn dispatch(ext: &mut Externalities<Blake2Hasher>, method: &str, data: &[u8]) -> Result<Vec<u8>>;
fn dispatch(ext: &mut dyn Externalities<Blake2Hasher>, method: &str, data: &[u8]) -> Result<Vec<u8>>;
/// Provide native runtime version.
fn native_version() -> NativeVersion;
+2 -2
View File
@@ -1101,7 +1101,7 @@ impl WasmExecutor {
/// This should be used for tests only.
pub fn call_with_custom_signature<
E: Externalities<Blake2Hasher>,
F: FnOnce(&mut FnMut(&[u8]) -> Result<u32>) -> Result<Vec<RuntimeValue>>,
F: FnOnce(&mut dyn FnMut(&[u8]) -> Result<u32>) -> Result<Vec<RuntimeValue>>,
FR: FnOnce(Option<RuntimeValue>, &MemoryRef) -> Result<Option<R>>,
R,
>(
@@ -1158,7 +1158,7 @@ impl WasmExecutor {
/// Call a given method in the given wasm-module runtime.
fn call_in_wasm_module_with_custom_signature<
E: Externalities<Blake2Hasher>,
F: FnOnce(&mut FnMut(&[u8]) -> Result<u32>) -> Result<Vec<RuntimeValue>>,
F: FnOnce(&mut dyn FnMut(&[u8]) -> Result<u32>) -> Result<Vec<RuntimeValue>>,
FR: FnOnce(Option<RuntimeValue>, &MemoryRef) -> Result<Option<R>>,
R,
>(
+1 -1
View File
@@ -174,7 +174,7 @@ macro_rules! impl_function_executor {
=> $($pre:tt)+ ) => (
impl $( $pre ) + $structname {
#[allow(unused)]
fn resolver() -> &'static $crate::wasmi::ModuleImportResolver {
fn resolver() -> &'static dyn $crate::wasmi::ModuleImportResolver {
struct Resolver;
impl $crate::wasmi::ModuleImportResolver for Resolver {
fn resolve_func(&self, name: &str, signature: &$crate::wasmi::Signature) -> ::std::result::Result<$crate::wasmi::FuncRef, $crate::wasmi::Error> {
@@ -657,7 +657,7 @@ impl<Block: BlockT> GossipValidator<Block> {
}
impl<Block: BlockT> network_gossip::Validator<Block> for GossipValidator<Block> {
fn new_peer(&self, context: &mut ValidatorContext<Block>, who: &PeerId, _roles: Roles) {
fn new_peer(&self, context: &mut dyn ValidatorContext<Block>, who: &PeerId, _roles: Roles) {
let packet_data = {
let mut inner = self.inner.write();
inner.peers.new_peer(who.clone());
@@ -673,11 +673,11 @@ impl<Block: BlockT> network_gossip::Validator<Block> for GossipValidator<Block>
context.send_message(who, packet_data);
}
fn peer_disconnected(&self, _context: &mut ValidatorContext<Block>, who: &PeerId) {
fn peer_disconnected(&self, _context: &mut dyn ValidatorContext<Block>, who: &PeerId) {
self.inner.write().peers.peer_disconnected(who);
}
fn validate(&self, context: &mut ValidatorContext<Block>, who: &PeerId, data: &[u8])
fn validate(&self, context: &mut dyn ValidatorContext<Block>, who: &PeerId, data: &[u8])
-> network_gossip::ValidationResult<Block::Hash>
{
let (action, broadcast_topics) = self.do_validate(who, data);
@@ -705,7 +705,7 @@ impl<Block: BlockT> network_gossip::Validator<Block> for GossipValidator<Block>
}
fn message_allowed<'a>(&'a self)
-> Box<FnMut(&PeerId, MessageIntent, &Block::Hash, &[u8]) -> bool + 'a>
-> Box<dyn FnMut(&PeerId, MessageIntent, &Block::Hash, &[u8]) -> bool + 'a>
{
let (inner, do_rebroadcast) = {
use parking_lot::RwLockWriteGuard;
@@ -763,7 +763,7 @@ impl<Block: BlockT> network_gossip::Validator<Block> for GossipValidator<Block>
})
}
fn message_expired<'a>(&'a self) -> Box<FnMut(Block::Hash, &[u8]) -> bool + 'a> {
fn message_expired<'a>(&'a self) -> Box<dyn FnMut(Block::Hash, &[u8]) -> bool + 'a> {
let inner = self.inner.read();
Box::new(move |topic, mut data| {
// if the topic is not one of the ones that we are keeping at the moment,
@@ -103,7 +103,7 @@ pub trait AuthoritySetForFinalityChecker<Block: BlockT>: Send + Sync {
}
/// FetchChecker-based implementation of AuthoritySetForFinalityChecker.
impl<Block: BlockT> AuthoritySetForFinalityChecker<Block> for Arc<FetchChecker<Block>> {
impl<Block: BlockT> AuthoritySetForFinalityChecker<Block> for Arc<dyn FetchChecker<Block>> {
fn check_authorities_proof(
&self,
hash: Block::Hash,
@@ -132,7 +132,7 @@ impl<Block: BlockT> AuthoritySetForFinalityChecker<Block> for Arc<FetchChecker<B
/// Finality proof provider for serving network requests.
pub struct FinalityProofProvider<B, E, Block: BlockT<Hash=H256>, RA> {
client: Arc<Client<B, E, Block, RA>>,
authority_provider: Arc<AuthoritySetForFinalityProver<Block>>,
authority_provider: Arc<dyn AuthoritySetForFinalityProver<Block>>,
}
impl<B, E, Block: BlockT<Hash=H256>, RA> FinalityProofProvider<B, E, Block, RA>
@@ -147,7 +147,7 @@ impl<B, E, Block: BlockT<Hash=H256>, RA> FinalityProofProvider<B, E, Block, RA>
/// - authority_provider for calling and proving runtime methods.
pub fn new(
client: Arc<Client<B, E, Block, RA>>,
authority_provider: Arc<AuthoritySetForFinalityProver<Block>>,
authority_provider: Arc<dyn AuthoritySetForFinalityProver<Block>>,
) -> Self {
FinalityProofProvider { client, authority_provider }
}
@@ -256,7 +256,7 @@ pub(crate) fn make_finality_proof_request<H: Encode + Decode>(last_finalized: H,
/// Returns None if there are no finalized blocks unknown to the caller.
pub(crate) fn prove_finality<Block: BlockT<Hash=H256>, B: BlockchainBackend<Block>, J>(
blockchain: &B,
authorities_provider: &AuthoritySetForFinalityProver<Block>,
authorities_provider: &dyn AuthoritySetForFinalityProver<Block>,
authorities_set_id: u64,
begin: Block::Hash,
end: Block::Hash,
@@ -416,7 +416,7 @@ pub(crate) fn check_finality_proof<Block: BlockT<Hash=H256>, B>(
blockchain: &B,
current_set_id: u64,
current_authorities: Vec<(AuthorityId, u64)>,
authorities_provider: &AuthoritySetForFinalityChecker<Block>,
authorities_provider: &dyn AuthoritySetForFinalityChecker<Block>,
remote_proof: Vec<u8>,
) -> ClientResult<FinalityEffects<Block::Header>>
where
@@ -435,7 +435,7 @@ fn do_check_finality_proof<Block: BlockT<Hash=H256>, B, J>(
blockchain: &B,
current_set_id: u64,
current_authorities: Vec<(AuthorityId, u64)>,
authorities_provider: &AuthoritySetForFinalityChecker<Block>,
authorities_provider: &dyn AuthoritySetForFinalityChecker<Block>,
remote_proof: Vec<u8>,
) -> ClientResult<FinalityEffects<Block::Header>>
where
@@ -489,7 +489,7 @@ fn do_check_finality_proof<Block: BlockT<Hash=H256>, B, J>(
fn check_finality_proof_fragment<Block: BlockT<Hash=H256>, B, J>(
blockchain: &B,
authority_set: AuthoritiesOrEffects<Block::Header>,
authorities_provider: &AuthoritySetForFinalityChecker<Block>,
authorities_provider: &dyn AuthoritySetForFinalityChecker<Block>,
proof_fragment: FinalityProofFragment<Block::Header>,
) -> ClientResult<AuthoritiesOrEffects<Block::Header>>
where
@@ -76,7 +76,7 @@ impl<B, E, Block: BlockT<Hash=H256>, RA, PRA, SC> JustificationImport<Block>
{
type Error = ConsensusError;
fn on_start(&self, link: &::consensus_common::import_queue::Link<Block>) {
fn on_start(&self, link: &dyn consensus_common::import_queue::Link<Block>) {
let chain_info = self.inner.info().chain;
// request justifications for all pending changes for which change blocks have already been imported
@@ -183,7 +183,7 @@ where
);
match maybe_change {
Err(e) => match api.has_api_with::<GrandpaApi<Block>, _>(&at, |v| v >= 2) {
Err(e) => match api.has_api_with::<dyn GrandpaApi<Block>, _>(&at, |v| v >= 2) {
Err(e) => return Err(ConsensusError::ClientImport(e.to_string()).into()),
Ok(true) => {
// API version is high enough to support forced changes
@@ -53,7 +53,7 @@ const LIGHT_CONSENSUS_CHANGES_KEY: &[u8] = b"grandpa_consensus_changes";
/// Create light block importer.
pub fn light_block_import<B, E, Block: BlockT<Hash=H256>, RA, PRA>(
client: Arc<Client<B, E, Block, RA>>,
authority_set_provider: Arc<AuthoritySetForFinalityChecker<Block>>,
authority_set_provider: Arc<dyn AuthoritySetForFinalityChecker<Block>>,
api: Arc<PRA>,
) -> Result<GrandpaLightBlockImport<B, E, Block, RA>, ClientError>
where
@@ -80,7 +80,7 @@ pub fn light_block_import<B, E, Block: BlockT<Hash=H256>, RA, PRA>(
/// - fetching finality proofs for blocks that are enacting consensus changes.
pub struct GrandpaLightBlockImport<B, E, Block: BlockT<Hash=H256>, RA> {
client: Arc<Client<B, E, Block, RA>>,
authority_set_provider: Arc<AuthoritySetForFinalityChecker<Block>>,
authority_set_provider: Arc<dyn AuthoritySetForFinalityChecker<Block>>,
data: Arc<RwLock<LightImportData<Block>>>,
}
@@ -144,7 +144,7 @@ impl<B, E, Block: BlockT<Hash=H256>, RA> FinalityProofImport<Block>
{
type Error = ConsensusError;
fn on_start(&self, link: &::consensus_common::import_queue::Link<Block>) {
fn on_start(&self, link: &dyn consensus_common::import_queue::Link<Block>) {
let chain_info = self.client.info().chain;
let data = self.data.read();
@@ -160,7 +160,7 @@ impl<B, E, Block: BlockT<Hash=H256>, RA> FinalityProofImport<Block>
hash: Block::Hash,
number: NumberFor<Block>,
finality_proof: Vec<u8>,
verifier: &Verifier<Block>,
verifier: &dyn Verifier<Block>,
) -> Result<(Block::Hash, NumberFor<Block>), Self::Error> {
do_import_finality_proof::<_, _, _, _, GrandpaJustification<Block>>(
&*self.client,
@@ -271,12 +271,12 @@ fn do_import_block<B, E, Block: BlockT<Hash=H256>, RA, J>(
/// Try to import finality proof.
fn do_import_finality_proof<B, E, Block: BlockT<Hash=H256>, RA, J>(
client: &Client<B, E, Block, RA>,
authority_set_provider: &AuthoritySetForFinalityChecker<Block>,
authority_set_provider: &dyn AuthoritySetForFinalityChecker<Block>,
data: &mut LightImportData<Block>,
_hash: Block::Hash,
_number: NumberFor<Block>,
finality_proof: Vec<u8>,
verifier: &Verifier<Block>,
verifier: &dyn Verifier<Block>,
) -> Result<(Block::Hash, NumberFor<Block>), ConsensusError>
where
B: Backend<Block, Blake2Hasher> + 'static,
@@ -572,7 +572,7 @@ pub mod tests {
{
type Error = ConsensusError;
fn on_start(&self, link: &::consensus_common::import_queue::Link<Block>) {
fn on_start(&self, link: &dyn consensus_common::import_queue::Link<Block>) {
self.0.on_start(link)
}
@@ -581,7 +581,7 @@ pub mod tests {
hash: Block::Hash,
number: NumberFor<Block>,
finality_proof: Vec<u8>,
verifier: &Verifier<Block>,
verifier: &dyn Verifier<Block>,
) -> Result<(Block::Hash, NumberFor<Block>), Self::Error> {
self.0.import_finality_proof(hash, number, finality_proof, verifier)
}
@@ -590,7 +590,7 @@ pub mod tests {
/// Creates light block import that ignores justifications that came outside of finality proofs.
pub fn light_block_import_without_justifications<B, E, Block: BlockT<Hash=H256>, RA, PRA>(
client: Arc<Client<B, E, Block, RA>>,
authority_set_provider: Arc<AuthoritySetForFinalityChecker<Block>>,
authority_set_provider: Arc<dyn AuthoritySetForFinalityChecker<Block>>,
api: Arc<PRA>,
) -> Result<NoJustificationsImport<B, E, Block, RA>, ClientError>
where
+6 -3
View File
@@ -150,7 +150,10 @@ impl TestNetFactory for GrandpaTestNet {
}
}
fn make_finality_proof_provider(&self, client: PeersClient) -> Option<Arc<network::FinalityProofProvider<Block>>> {
fn make_finality_proof_provider(
&self,
client: PeersClient
) -> Option<Arc<dyn network::FinalityProofProvider<Block>>> {
match client {
PeersClient::Full(ref client) => {
let authorities_provider = Arc::new(self.test_config.clone());
@@ -201,7 +204,7 @@ impl MessageRouting {
}
impl Network<Block> for MessageRouting {
type In = Box<Stream<Item=network_gossip::TopicNotification, Error=()> + Send>;
type In = Box<dyn Stream<Item=network_gossip::TopicNotification, Error=()> + Send>;
/// Get a stream of messages for a specific gossip topic.
fn messages_for(&self, topic: Hash) -> Self::In {
@@ -463,7 +466,7 @@ fn run_to_completion_with<F>(
peers: &[AuthorityKeyring],
with: F,
) -> u64 where
F: FnOnce(current_thread::Handle) -> Option<Box<Future<Item=(),Error=()>>>
F: FnOnce(current_thread::Handle) -> Option<Box<dyn Future<Item=(), Error=()>>>
{
use parking_lot::RwLock;
+1 -1
View File
@@ -68,7 +68,7 @@ impl Keyring {
}
pub fn to_raw_public_vec(self) -> Vec<u8> {
Public::from(self).to_raw_vec()
Public::from(self).into_raw_vec()
}
pub fn sign(self, msg: &[u8]) -> Signature {
+3 -3
View File
@@ -35,9 +35,9 @@ pub struct Params<B: BlockT, S, H: ExHashT> {
/// Network layer configuration.
pub network_config: NetworkConfiguration,
/// Substrate relay chain access point.
pub chain: Arc<Client<B>>,
pub chain: Arc<dyn Client<B>>,
/// Finality proof provider.
pub finality_proof_provider: Option<Arc<FinalityProofProvider<B>>>,
pub finality_proof_provider: Option<Arc<dyn FinalityProofProvider<B>>>,
/// On-demand service reference.
pub on_demand: Option<Arc<OnDemand<B>>>,
/// Transaction pool.
@@ -45,7 +45,7 @@ pub struct Params<B: BlockT, S, H: ExHashT> {
/// Name of the protocol to use on the wire. Should be different for each chain.
pub protocol_id: ProtocolId,
/// Import queue to use.
pub import_queue: Box<ImportQueue<B>>,
pub import_queue: Box<dyn ImportQueue<B>>,
/// Protocol specialization.
pub specialization: S,
}
+45 -23
View File
@@ -110,7 +110,7 @@ pub trait ValidatorContext<B: BlockT> {
struct NetworkContext<'g, 'p, B: BlockT> {
gossip: &'g mut ConsensusGossip<B>,
protocol: &'p mut Context<B>,
protocol: &'p mut dyn Context<B>,
engine_id: ConsensusEngineId,
}
@@ -145,11 +145,11 @@ impl<'g, 'p, B: BlockT> ValidatorContext<B> for NetworkContext<'g, 'p, B> {
}
fn propagate<'a, B: BlockT, I>(
protocol: &mut Context<B>,
protocol: &mut dyn Context<B>,
messages: I,
intent: MessageIntent,
peers: &mut HashMap<PeerId, PeerConsensus<B::Hash>>,
validators: &HashMap<ConsensusEngineId, Arc<Validator<B>>>,
validators: &HashMap<ConsensusEngineId, Arc<dyn Validator<B>>>,
)
where I: IntoIterator<Item=(&'a B::Hash, &'a B::Hash, &'a ConsensusMessage)>, // (msg_hash, topic, message)
{
@@ -200,23 +200,23 @@ fn propagate<'a, B: BlockT, I>(
/// Validates consensus messages.
pub trait Validator<B: BlockT>: Send + Sync {
/// New peer is connected.
fn new_peer(&self, _context: &mut ValidatorContext<B>, _who: &PeerId, _roles: Roles) {
fn new_peer(&self, _context: &mut dyn ValidatorContext<B>, _who: &PeerId, _roles: Roles) {
}
/// New connection is dropped.
fn peer_disconnected(&self, _context: &mut ValidatorContext<B>, _who: &PeerId) {
fn peer_disconnected(&self, _context: &mut dyn ValidatorContext<B>, _who: &PeerId) {
}
/// Validate consensus message.
fn validate(&self, context: &mut ValidatorContext<B>, sender: &PeerId, data: &[u8]) -> ValidationResult<B::Hash>;
fn validate(&self, context: &mut dyn ValidatorContext<B>, sender: &PeerId, data: &[u8]) -> ValidationResult<B::Hash>;
/// Produce a closure for validating messages on a given topic.
fn message_expired<'a>(&'a self) -> Box<FnMut(B::Hash, &[u8]) -> bool + 'a> {
fn message_expired<'a>(&'a self) -> Box<dyn FnMut(B::Hash, &[u8]) -> bool + 'a> {
Box::new(move |_topic, _data| false)
}
/// Produce a closure for filtering egress messages.
fn message_allowed<'a>(&'a self) -> Box<FnMut(&PeerId, MessageIntent, &B::Hash, &[u8]) -> bool + 'a> {
fn message_allowed<'a>(&'a self) -> Box<dyn FnMut(&PeerId, MessageIntent, &B::Hash, &[u8]) -> bool + 'a> {
Box::new(move |_who, _intent, _topic, _data| true)
}
}
@@ -227,7 +227,7 @@ pub struct ConsensusGossip<B: BlockT> {
live_message_sinks: HashMap<(ConsensusEngineId, B::Hash), Vec<mpsc::UnboundedSender<TopicNotification>>>,
messages: Vec<MessageEntry<B>>,
known_messages: LruCache<B::Hash, ()>,
validators: HashMap<ConsensusEngineId, Arc<Validator<B>>>,
validators: HashMap<ConsensusEngineId, Arc<dyn Validator<B>>>,
next_broadcast: time::Instant,
}
@@ -250,7 +250,12 @@ impl<B: BlockT> ConsensusGossip<B> {
}
/// Register message validator for a message type.
pub fn register_validator(&mut self, protocol: &mut Context<B>, engine_id: ConsensusEngineId, validator: Arc<Validator<B>>) {
pub fn register_validator(
&mut self,
protocol: &mut dyn Context<B>,
engine_id: ConsensusEngineId,
validator: Arc<dyn Validator<B>>
) {
self.register_validator_internal(engine_id, validator.clone());
let peers: Vec<_> = self.peers.iter().map(|(id, peer)| (id.clone(), peer.roles)).collect();
for (id, roles) in peers {
@@ -259,12 +264,12 @@ impl<B: BlockT> ConsensusGossip<B> {
}
}
fn register_validator_internal(&mut self, engine_id: ConsensusEngineId, validator: Arc<Validator<B>>) {
fn register_validator_internal(&mut self, engine_id: ConsensusEngineId, validator: Arc<dyn Validator<B>>) {
self.validators.insert(engine_id, validator.clone());
}
/// Handle new connected peer.
pub fn new_peer(&mut self, protocol: &mut Context<B>, who: PeerId, roles: Roles) {
pub fn new_peer(&mut self, protocol: &mut dyn Context<B>, who: PeerId, roles: Roles) {
// light nodes are not valid targets for consensus gossip messages
if !roles.is_full() {
return;
@@ -311,7 +316,7 @@ impl<B: BlockT> ConsensusGossip<B> {
}
/// Call when a peer has been disconnected to stop tracking gossip status.
pub fn peer_disconnected(&mut self, protocol: &mut Context<B>, who: PeerId) {
pub fn peer_disconnected(&mut self, protocol: &mut dyn Context<B>, who: PeerId) {
for (engine_id, v) in self.validators.clone() {
let mut context = NetworkContext { gossip: self, protocol, engine_id: engine_id.clone() };
v.peer_disconnected(&mut context, &who);
@@ -319,7 +324,7 @@ impl<B: BlockT> ConsensusGossip<B> {
}
/// Perform periodic maintenance
pub fn tick(&mut self, protocol: &mut Context<B>) {
pub fn tick(&mut self, protocol: &mut dyn Context<B>) {
self.collect_garbage();
if time::Instant::now() >= self.next_broadcast {
self.rebroadcast(protocol);
@@ -328,14 +333,14 @@ impl<B: BlockT> ConsensusGossip<B> {
}
/// Rebroadcast all messages to all peers.
fn rebroadcast(&mut self, protocol: &mut Context<B>) {
fn rebroadcast(&mut self, protocol: &mut dyn Context<B>) {
let messages = self.messages.iter()
.map(|entry| (&entry.message_hash, &entry.topic, &entry.message));
propagate(protocol, messages, MessageIntent::PeriodicRebroadcast, &mut self.peers, &self.validators);
}
/// Broadcast all messages with given topic.
pub fn broadcast_topic(&mut self, protocol: &mut Context<B>, topic: B::Hash, force: bool) {
pub fn broadcast_topic(&mut self, protocol: &mut dyn Context<B>, topic: B::Hash, force: bool) {
let messages = self.messages.iter()
.filter_map(|entry|
if entry.topic == topic { Some((&entry.message_hash, &entry.topic, &entry.message)) } else { None }
@@ -409,7 +414,7 @@ impl<B: BlockT> ConsensusGossip<B> {
/// in all other cases.
pub fn on_incoming(
&mut self,
protocol: &mut Context<B>,
protocol: &mut dyn Context<B>,
who: PeerId,
message: ConsensusMessage,
) {
@@ -473,7 +478,14 @@ impl<B: BlockT> ConsensusGossip<B> {
}
/// Send all messages with given topic to a peer.
pub fn send_topic(&mut self, protocol: &mut Context<B>, who: &PeerId, topic: B::Hash, engine_id: ConsensusEngineId, force: bool) {
pub fn send_topic(
&mut self,
protocol: &mut dyn Context<B>,
who: &PeerId,
topic: B::Hash,
engine_id: ConsensusEngineId,
force: bool
) {
let validator = self.validators.get(&engine_id);
let mut message_allowed = match validator {
None => return, // treat all messages with no validator as not allowed
@@ -503,7 +515,7 @@ impl<B: BlockT> ConsensusGossip<B> {
/// Multicast a message to all peers.
pub fn multicast(
&mut self,
protocol: &mut Context<B>,
protocol: &mut dyn Context<B>,
topic: B::Hash,
message: ConsensusMessage,
force: bool,
@@ -518,7 +530,7 @@ impl<B: BlockT> ConsensusGossip<B> {
/// later on.
pub fn send_message(
&mut self,
protocol: &mut Context<B>,
protocol: &mut dyn Context<B>,
who: &PeerId,
message: ConsensusMessage,
) {
@@ -559,7 +571,12 @@ mod tests {
struct AllowAll;
impl Validator<Block> for AllowAll {
fn validate(&self, _context: &mut ValidatorContext<Block>, _sender: &PeerId, _data: &[u8]) -> ValidationResult<H256> {
fn validate(
&self,
_context: &mut dyn ValidatorContext<Block>,
_sender: &PeerId,
_data: &[u8],
) -> ValidationResult<H256> {
ValidationResult::ProcessAndKeep(H256::default())
}
}
@@ -568,7 +585,12 @@ mod tests {
fn collects_garbage() {
struct AllowOne;
impl Validator<Block> for AllowOne {
fn validate(&self, _context: &mut ValidatorContext<Block>, _sender: &PeerId, data: &[u8]) -> ValidationResult<H256> {
fn validate(
&self,
_context: &mut dyn ValidatorContext<Block>,
_sender: &PeerId,
data: &[u8],
) -> ValidationResult<H256> {
if data[0] == 1 {
ValidationResult::ProcessAndKeep(H256::default())
} else {
@@ -576,7 +598,7 @@ mod tests {
}
}
fn message_expired<'a>(&'a self) -> Box<FnMut(H256, &[u8]) -> bool + 'a> {
fn message_expired<'a>(&'a self) -> Box<dyn FnMut(H256, &[u8]) -> bool + 'a> {
Box::new(move |_topic, data| data[0] != 1 )
}
}
@@ -50,7 +50,7 @@ impl<B: BlockT> OnDemand<B> where
B::Header: HeaderT,
{
/// Creates new on-demand service.
pub fn new(checker: Arc<FetchChecker<B>>) -> Self {
pub fn new(checker: Arc<dyn FetchChecker<B>>) -> Self {
let (requests_send, requests_queue) = mpsc::unbounded();
let requests_queue = Mutex::new(Some(requests_queue));
@@ -62,7 +62,7 @@ impl<B: BlockT> OnDemand<B> where
}
/// Get checker reference.
pub fn checker(&self) -> &Arc<FetchChecker<B>> {
pub fn checker(&self) -> &Arc<dyn FetchChecker<B>> {
&self.checker
}
+5 -5
View File
@@ -346,7 +346,7 @@ impl<'a, B: BlockT + 'a, H: ExHashT + 'a> SyncContext<B> for ProtocolContext<'a,
self.context_data.peers.get(who).map(|p| p.info.clone())
}
fn client(&self) -> &Client<B> {
fn client(&self) -> &dyn Client<B> {
&*self.context_data.chain
}
@@ -373,7 +373,7 @@ impl<'a, B: BlockT + 'a, H: ExHashT + 'a> SyncContext<B> for ProtocolContext<'a,
struct ContextData<B: BlockT, H: ExHashT> {
// All connected peers
peers: HashMap<PeerId, Peer<B, H>>,
pub chain: Arc<Client<B>>,
pub chain: Arc<dyn Client<B>>,
}
/// Configuration for the Substrate-specific part of the networking layer.
@@ -395,7 +395,7 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
/// Create a new instance.
pub fn new(
config: ProtocolConfig,
chain: Arc<Client<B>>,
chain: Arc<dyn Client<B>>,
checker: Arc<dyn FetchChecker<B>>,
specialization: S,
) -> error::Result<Protocol<B, S, H>> {
@@ -510,7 +510,7 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
transaction_pool: &(impl TransactionPool<H, B> + ?Sized),
who: PeerId,
message: Message<B>,
finality_proof_provider: Option<&FinalityProofProvider<B>>
finality_proof_provider: Option<&dyn FinalityProofProvider<B>>
) -> CustomMessageOutcome<B> {
match message {
GenericMessage::Status(s) => self.on_status_message(network_out, who, s),
@@ -1399,7 +1399,7 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
network_out: &mut dyn NetworkOut<B>,
who: PeerId,
request: message::FinalityProofRequest<B::Hash>,
finality_proof_provider: Option<&FinalityProofProvider<B>>
finality_proof_provider: Option<&dyn FinalityProofProvider<B>>
) {
trace!(target: "sync", "Finality proof request from {} for {}", who, request.block);
let finality_proof = finality_proof_provider.as_ref()
+12 -12
View File
@@ -358,7 +358,7 @@ impl<B: BlockT + 'static, S: NetworkSpecialization<B>> NetworkService<B, S> {
/// Execute a closure with the chain-specific network specialization.
pub fn with_spec<F>(&self, f: F)
where F: FnOnce(&mut S, &mut Context<B>) + Send + 'static
where F: FnOnce(&mut S, &mut dyn Context<B>) + Send + 'static
{
let _ = self
.protocol_sender
@@ -367,7 +367,7 @@ impl<B: BlockT + 'static, S: NetworkSpecialization<B>> NetworkService<B, S> {
/// Execute a closure with the consensus gossip.
pub fn with_gossip<F>(&self, f: F)
where F: FnOnce(&mut ConsensusGossip<B>, &mut Context<B>) + Send + 'static
where F: FnOnce(&mut ConsensusGossip<B>, &mut dyn Context<B>) + Send + 'static
{
let _ = self
.protocol_sender
@@ -489,9 +489,9 @@ pub enum ProtocolMsg<B: BlockT, S: NetworkSpecialization<B>> {
/// A block has been finalized (sent by the client).
BlockFinalized(B::Hash, B::Header),
/// Execute a closure with the chain-specific network specialization.
ExecuteWithSpec(Box<SpecTask<B, S> + Send + 'static>),
ExecuteWithSpec(Box<dyn SpecTask<B, S> + Send + 'static>),
/// Execute a closure with the consensus gossip.
ExecuteWithGossip(Box<GossipTask<B> + Send + 'static>),
ExecuteWithGossip(Box<dyn GossipTask<B> + Send + 'static>),
/// Incoming gossip consensus message.
GossipConsensusMessage(B::Hash, ConsensusEngineId, Vec<u8>, GossipMessageRecipient),
/// Tell protocol to perform regular maintenance.
@@ -504,22 +504,22 @@ pub enum ProtocolMsg<B: BlockT, S: NetworkSpecialization<B>> {
/// A task, consisting of a user-provided closure, to be executed on the Protocol thread.
pub trait SpecTask<B: BlockT, S: NetworkSpecialization<B>> {
fn call_box(self: Box<Self>, spec: &mut S, context: &mut Context<B>);
fn call_box(self: Box<Self>, spec: &mut S, context: &mut dyn Context<B>);
}
impl<B: BlockT, S: NetworkSpecialization<B>, F: FnOnce(&mut S, &mut Context<B>)> SpecTask<B, S> for F {
fn call_box(self: Box<F>, spec: &mut S, context: &mut Context<B>) {
impl<B: BlockT, S: NetworkSpecialization<B>, F: FnOnce(&mut S, &mut dyn Context<B>)> SpecTask<B, S> for F {
fn call_box(self: Box<F>, spec: &mut S, context: &mut dyn Context<B>) {
(*self)(spec, context)
}
}
/// A task, consisting of a user-provided closure, to be executed on the Protocol thread.
pub trait GossipTask<B: BlockT> {
fn call_box(self: Box<Self>, gossip: &mut ConsensusGossip<B>, context: &mut Context<B>);
fn call_box(self: Box<Self>, gossip: &mut ConsensusGossip<B>, context: &mut dyn Context<B>);
}
impl<B: BlockT, F: FnOnce(&mut ConsensusGossip<B>, &mut Context<B>)> GossipTask<B> for F {
fn call_box(self: Box<F>, gossip: &mut ConsensusGossip<B>, context: &mut Context<B>) {
impl<B: BlockT, F: FnOnce(&mut ConsensusGossip<B>, &mut dyn Context<B>)> GossipTask<B> for F {
fn call_box(self: Box<F>, gossip: &mut ConsensusGossip<B>, context: &mut dyn Context<B>) {
(*self)(gossip, context)
}
}
@@ -535,9 +535,9 @@ pub struct NetworkWorker<B: BlockT + 'static, S: NetworkSpecialization<B>, H: Ex
service: Arc<NetworkService<B, S>>,
network_service: Arc<Mutex<Libp2pNetService<Message<B>>>>,
peers: Arc<RwLock<HashMap<PeerId, ConnectedPeer<B>>>>,
import_queue: Box<ImportQueue<B>>,
import_queue: Box<dyn ImportQueue<B>>,
transaction_pool: Arc<dyn TransactionPool<H, B>>,
finality_proof_provider: Option<Arc<FinalityProofProvider<B>>>,
finality_proof_provider: Option<Arc<dyn FinalityProofProvider<B>>>,
network_port: mpsc::UnboundedReceiver<NetworkMsg<B>>,
protocol_rx: mpsc::UnboundedReceiver<ProtocolMsg<B, S>>,
status_sinks: Arc<Mutex<Vec<mpsc::UnboundedSender<ProtocolStatus<B>>>>>,
+5 -5
View File
@@ -25,15 +25,15 @@ pub trait NetworkSpecialization<B: BlockT>: Send + Sync + 'static {
fn status(&self) -> Vec<u8>;
/// Called when a peer successfully handshakes.
fn on_connect(&mut self, ctx: &mut Context<B>, who: PeerId, status: crate::message::Status<B>);
fn on_connect(&mut self, ctx: &mut dyn Context<B>, who: PeerId, status: crate::message::Status<B>);
/// Called when a peer is disconnected. If the peer ID is unknown, it should be ignored.
fn on_disconnect(&mut self, ctx: &mut Context<B>, who: PeerId);
fn on_disconnect(&mut self, ctx: &mut dyn Context<B>, who: PeerId);
/// Called when a network-specific message arrives.
fn on_message(
&mut self,
ctx: &mut Context<B>,
ctx: &mut dyn Context<B>,
who: PeerId,
message: &mut Option<crate::message::Message<B>>
);
@@ -43,11 +43,11 @@ pub trait NetworkSpecialization<B: BlockT>: Send + Sync + 'static {
fn on_abort(&mut self) { }
/// Called periodically to maintain peers and handle timeouts.
fn maintain_peers(&mut self, _ctx: &mut Context<B>) { }
fn maintain_peers(&mut self, _ctx: &mut dyn Context<B>) { }
/// Called when a block is _imported_ at the head of the chain (not during major sync).
/// Not guaranteed to be called for every block, but will be most of the after major sync.
fn on_block_imported(&mut self, _ctx: &mut Context<B>, _hash: B::Hash, _header: &B::Header) { }
fn on_block_imported(&mut self, _ctx: &mut dyn Context<B>, _hash: B::Hash, _header: &B::Header) { }
}
/// Context for a network-specific handler.
+20 -20
View File
@@ -72,7 +72,7 @@ const GENESIS_MISMATCH_REPUTATION_CHANGE: i32 = i32::min_value() + 1;
/// Context for a network-specific handler.
pub trait Context<B: BlockT> {
/// Get a reference to the client.
fn client(&self) -> &crate::chain::Client<B>;
fn client(&self) -> &dyn crate::chain::Client<B>;
/// Adjusts the reputation of the peer. Use this to point out that a peer has been malign or
/// irresponsible or appeared lazy.
@@ -131,7 +131,7 @@ pub(crate) enum PeerSyncState<B: BlockT> {
/// Relay chain sync strategy.
pub struct ChainSync<B: BlockT> {
genesis_hash: B::Hash,
_genesis_hash: B::Hash,
peers: HashMap<PeerId, PeerSync<B>>,
blocks: BlockCollection<B>,
best_queued_number: NumberFor<B>,
@@ -191,7 +191,7 @@ impl<B: BlockT> ChainSync<B> {
}
ChainSync {
genesis_hash: info.chain.genesis_hash,
_genesis_hash: info.chain.genesis_hash,
peers: HashMap::new(),
blocks: BlockCollection::new(),
best_queued_hash: info.best_queued_hash.unwrap_or(info.chain.best_hash),
@@ -230,14 +230,14 @@ impl<B: BlockT> ChainSync<B> {
let best_seen = self.best_seen_block();
let state = self.state(&best_seen);
Status {
state: state,
state,
best_seen_block: best_seen,
num_peers: self.peers.len() as u32,
}
}
/// Handle new connected peer. Call this method whenever we connect to a new peer.
pub(crate) fn new_peer(&mut self, protocol: &mut Context<B>, who: PeerId) {
pub(crate) fn new_peer(&mut self, protocol: &mut dyn Context<B>, who: PeerId) {
if let Some(info) = protocol.peer_info(&who) {
// there's nothing sync can get from the node that has no blockchain data
// (the opposite is not true, but all requests are served at protocol level)
@@ -366,7 +366,7 @@ impl<B: BlockT> ChainSync<B> {
#[must_use]
pub(crate) fn on_block_data(
&mut self,
protocol: &mut Context<B>,
protocol: &mut dyn Context<B>,
who: PeerId,
request: message::BlockRequest<B>,
response: message::BlockResponse<B>
@@ -483,7 +483,7 @@ impl<B: BlockT> ChainSync<B> {
#[must_use]
pub(crate) fn on_block_justification_data(
&mut self,
protocol: &mut Context<B>,
protocol: &mut dyn Context<B>,
who: PeerId,
_request: message::BlockRequest<B>,
response: message::BlockResponse<B>,
@@ -528,7 +528,7 @@ impl<B: BlockT> ChainSync<B> {
/// Handle new finality proof data.
pub(crate) fn on_block_finality_proof_data(
&mut self,
protocol: &mut Context<B>,
protocol: &mut dyn Context<B>,
who: PeerId,
response: message::FinalityProofResponse<B::Hash>,
) -> Option<(PeerId, B::Hash, NumberFor<B>, Vec<u8>)> {
@@ -573,7 +573,7 @@ impl<B: BlockT> ChainSync<B> {
}
/// Maintain the sync process (download new blocks, fetch justifications).
pub fn maintain_sync(&mut self, protocol: &mut Context<B>) {
pub fn maintain_sync(&mut self, protocol: &mut dyn Context<B>) {
let peers: Vec<PeerId> = self.peers.keys().map(|p| p.clone()).collect();
for peer in peers {
self.download_new(protocol, peer);
@@ -583,7 +583,7 @@ impl<B: BlockT> ChainSync<B> {
/// Called periodically to perform any time-based actions. Must be called at a regular
/// interval.
pub fn tick(&mut self, protocol: &mut Context<B>) {
pub fn tick(&mut self, protocol: &mut dyn Context<B>) {
self.extra_requests.dispatch(&mut self.peers, protocol);
}
@@ -591,7 +591,7 @@ impl<B: BlockT> ChainSync<B> {
///
/// Uses `protocol` to queue a new justification request and tries to dispatch all pending
/// requests.
pub fn request_justification(&mut self, hash: &B::Hash, number: NumberFor<B>, protocol: &mut Context<B>) {
pub fn request_justification(&mut self, hash: &B::Hash, number: NumberFor<B>, protocol: &mut dyn Context<B>) {
self.extra_requests.justifications().queue_request(
(*hash, number),
|base, block| protocol.client().is_descendent_of(base, block),
@@ -620,7 +620,7 @@ impl<B: BlockT> ChainSync<B> {
/// Request a finality proof for the given block.
///
/// Queues a new finality proof request and tries to dispatch all pending requests.
pub fn request_finality_proof(&mut self, hash: &B::Hash, number: NumberFor<B>, protocol: &mut Context<B>) {
pub fn request_finality_proof(&mut self, hash: &B::Hash, number: NumberFor<B>, protocol: &mut dyn Context<B>) {
self.extra_requests.finality_proofs().queue_request(
(*hash, number),
|base, block| protocol.client().is_descendent_of(base, block),
@@ -647,7 +647,7 @@ impl<B: BlockT> ChainSync<B> {
}
/// Notify about finalization of the given block.
pub fn on_block_finalized(&mut self, hash: &B::Hash, number: NumberFor<B>, protocol: &mut Context<B>) {
pub fn on_block_finalized(&mut self, hash: &B::Hash, number: NumberFor<B>, protocol: &mut dyn Context<B>) {
if let Err(err) = self.extra_requests.on_block_finalized(
hash,
number,
@@ -699,7 +699,7 @@ impl<B: BlockT> ChainSync<B> {
#[must_use]
pub(crate) fn on_block_announce(
&mut self,
protocol: &mut Context<B>,
protocol: &mut dyn Context<B>,
who: PeerId,
hash: B::Hash,
header: &B::Header,
@@ -812,12 +812,12 @@ impl<B: BlockT> ChainSync<B> {
self.peers.iter().any(|(_, p)| p.state == PeerSyncState::DownloadingStale(*hash))
}
fn is_known(&self, protocol: &mut Context<B>, hash: &B::Hash) -> bool {
fn is_known(&self, protocol: &mut dyn Context<B>, hash: &B::Hash) -> bool {
block_status(&*protocol.client(), &self.queue_blocks, *hash).ok().map_or(false, |s| s != BlockStatus::Unknown)
}
/// Call when a peer has disconnected.
pub(crate) fn peer_disconnected(&mut self, protocol: &mut Context<B>, who: PeerId) {
pub(crate) fn peer_disconnected(&mut self, protocol: &mut dyn Context<B>, who: PeerId) {
self.blocks.clear_peer_download(&who);
self.peers.remove(&who);
self.extra_requests.peer_disconnected(who);
@@ -825,7 +825,7 @@ impl<B: BlockT> ChainSync<B> {
}
/// Restart the sync process.
pub(crate) fn restart(&mut self, protocol: &mut Context<B>) {
pub(crate) fn restart(&mut self, protocol: &mut dyn Context<B>) {
self.queue_blocks.clear();
self.best_importing_number = Zero::zero();
self.blocks.clear();
@@ -886,7 +886,7 @@ impl<B: BlockT> ChainSync<B> {
}
// Issue a request for a peer to download new blocks, if any are available.
fn download_new(&mut self, protocol: &mut Context<B>, who: PeerId) {
fn download_new(&mut self, protocol: &mut dyn Context<B>, who: PeerId) {
if let Some((_, request)) = self.select_new_blocks(who.clone()) {
protocol.send_block_request(who, request);
}
@@ -942,7 +942,7 @@ impl<B: BlockT> ChainSync<B> {
}
}
fn request_ancestry(protocol: &mut Context<B>, who: PeerId, block: NumberFor<B>) {
fn request_ancestry(protocol: &mut dyn Context<B>, who: PeerId, block: NumberFor<B>) {
trace!(target: "sync", "Requesting ancestry block #{} from {}", block, who);
let request = message::generic::BlockRequest {
id: 0,
@@ -958,7 +958,7 @@ impl<B: BlockT> ChainSync<B> {
/// Get block status, taking into account import queue.
fn block_status<B: BlockT>(
chain: &crate::chain::Client<B>,
chain: &dyn crate::chain::Client<B>,
queue_blocks: &HashSet<B::Hash>,
hash: B::Hash) -> Result<BlockStatus, ClientError>
{
@@ -39,7 +39,7 @@ pub(crate) trait ExtraRequestsEssence<B: BlockT> {
/// Name of request type to display in logs.
fn type_name(&self) -> &'static str;
/// Send network message corresponding to the request.
fn send_network_request(&self, protocol: &mut Context<B>, peer: PeerId, request: ExtraRequest<B>);
fn send_network_request(&self, protocol: &mut dyn Context<B>, peer: PeerId, request: ExtraRequest<B>);
/// Create peer state for peer that is downloading extra data.
fn peer_downloading_state(&self, block: B::Hash) -> PeerSyncState<B>;
}
@@ -69,7 +69,7 @@ impl<B: BlockT> ExtraRequestsAggregator<B> {
}
/// Dispatches all possible pending requests to the given peers.
pub(crate) fn dispatch(&mut self, peers: &mut HashMap<PeerId, PeerSync<B>>, protocol: &mut Context<B>) {
pub(crate) fn dispatch(&mut self, peers: &mut HashMap<PeerId, PeerSync<B>>, protocol: &mut dyn Context<B>) {
self.justifications.dispatch(peers, protocol);
self.finality_proofs.dispatch(peers, protocol);
}
@@ -132,7 +132,7 @@ impl<B: BlockT, Essence: ExtraRequestsEssence<B>> ExtraRequests<B, Essence> {
/// extra request for block #10 to a peer at block #2), and we also
/// throttle requests to the same peer if a previous justification request
/// yielded no results.
pub(crate) fn dispatch(&mut self, peers: &mut HashMap<PeerId, PeerSync<B>>, protocol: &mut Context<B>) {
pub(crate) fn dispatch(&mut self, peers: &mut HashMap<PeerId, PeerSync<B>>, protocol: &mut dyn Context<B>) {
if self.pending_requests.is_empty() {
return;
}
@@ -373,7 +373,7 @@ impl<B: BlockT> ExtraRequestsEssence<B> for JustificationsRequestsEssence {
"justification"
}
fn send_network_request(&self, protocol: &mut Context<B>, peer: PeerId, request: ExtraRequest<B>) {
fn send_network_request(&self, protocol: &mut dyn Context<B>, peer: PeerId, request: ExtraRequest<B>) {
protocol.send_block_request(peer, message::generic::BlockRequest {
id: 0,
fields: message::BlockAttributes::JUSTIFICATION,
@@ -398,7 +398,7 @@ impl<B: BlockT> ExtraRequestsEssence<B> for FinalityProofRequestsEssence<B> {
"finality proof"
}
fn send_network_request(&self, protocol: &mut Context<B>, peer: PeerId, request: ExtraRequest<B>) {
fn send_network_request(&self, protocol: &mut dyn Context<B>, peer: PeerId, request: ExtraRequest<B>) {
protocol.send_finality_proof_request(peer, message::generic::FinalityProofRequest {
id: 0,
block: request.0,
+9 -12
View File
@@ -103,22 +103,19 @@ impl NetworkSpecialization<Block> for DummySpecialization {
fn on_connect(
&mut self,
_ctx: &mut SpecializationContext<Block>,
_ctx: &mut dyn SpecializationContext<Block>,
_peer_id: PeerId,
_status: crate::message::Status<Block>
) {
}
) {}
fn on_disconnect(&mut self, _ctx: &mut SpecializationContext<Block>, _peer_id: PeerId) {
}
fn on_disconnect(&mut self, _ctx: &mut dyn SpecializationContext<Block>, _peer_id: PeerId) {}
fn on_message(
&mut self,
_ctx: &mut SpecializationContext<Block>,
_ctx: &mut dyn SpecializationContext<Block>,
_peer_id: PeerId,
_message: &mut Option<crate::message::Message<Block>>,
) {
}
) {}
}
pub type PeersFullClient =
@@ -292,7 +289,7 @@ pub struct Peer<D, S: NetworkSpecialization<Block>> {
finalized_hash: Mutex<Option<H256>>,
}
type MessageFilter = Fn(&NetworkMsg<Block>) -> bool;
type MessageFilter = dyn Fn(&NetworkMsg<Block>) -> bool;
pub enum FromNetworkMsg<B: BlockT> {
/// A peer connected, with debug info.
@@ -605,7 +602,7 @@ impl<D, S: NetworkSpecialization<Block>> Peer<D, S> {
/// Execute a closure with the consensus gossip.
pub fn with_gossip<F>(&self, f: F)
where F: FnOnce(&mut ConsensusGossip<Block>, &mut Context<Block>) + Send + 'static
where F: FnOnce(&mut ConsensusGossip<Block>, &mut dyn Context<Block>) + Send + 'static
{
self.net_proto_channel.send_from_client(ProtocolMsg::ExecuteWithGossip(Box::new(f)));
}
@@ -767,7 +764,7 @@ pub trait TestNetFactory: Sized {
}
/// Get finality proof provider (if supported).
fn make_finality_proof_provider(&self, _client: PeersClient) -> Option<Arc<FinalityProofProvider<Block>>> {
fn make_finality_proof_provider(&self, _client: PeersClient) -> Option<Arc<dyn FinalityProofProvider<Block>>> {
None
}
@@ -799,7 +796,7 @@ pub trait TestNetFactory: Sized {
protocol_status: Arc<RwLock<ProtocolStatus<Block>>>,
import_queue: Box<BasicQueue<Block>>,
tx_pool: EmptyTransactionPool,
finality_proof_provider: Option<Arc<FinalityProofProvider<Block>>>,
finality_proof_provider: Option<Arc<dyn FinalityProofProvider<Block>>>,
mut protocol: Protocol<Block, Self::Specialization, Hash>,
network_sender: mpsc::UnboundedSender<NetworkMsg<Block>>,
mut network_to_protocol_rx: mpsc::UnboundedReceiver<FromNetworkMsg<Block>>,
+1 -1
View File
@@ -91,7 +91,7 @@ impl<C, Block> OffchainWorkers<C, Block> where
{
let runtime = self.client.runtime_api();
let at = BlockId::number(*number);
let has_api = runtime.has_api::<OffchainWorkerApi<Block>>(&at);
let has_api = runtime.has_api::<dyn OffchainWorkerApi<Block>>(&at);
debug!("Checking offchain workers at {:?}: {:?}", at, has_api);
if has_api.unwrap_or(false) {
+2 -2
View File
@@ -21,7 +21,7 @@ pub struct HexDisplay<'a>(&'a [u8]);
impl<'a> HexDisplay<'a> {
/// Create new instance that will display `d` as a hex string when displayed.
pub fn from(d: &'a AsBytesRef) -> Self { HexDisplay(d.as_bytes_ref()) }
pub fn from(d: &'a dyn AsBytesRef) -> Self { HexDisplay(d.as_bytes_ref()) }
}
impl<'a> ::core::fmt::Display for HexDisplay<'a> {
@@ -79,7 +79,7 @@ pub fn ascii_format(asciish: &[u8]) -> String {
let mut latch = false;
for c in asciish {
match (latch, *c) {
(false, 32...127) => r.push(*c as char),
(false, 32..=127) => r.push(*c as char),
_ => {
if !latch {
r.push('#');
+1 -1
View File
@@ -86,7 +86,7 @@ pub enum ExecutionContext {
/// Context used for block construction.
BlockConstruction,
/// Offchain worker context.
OffchainWorker(Box<offchain::Externalities>),
OffchainWorker(Box<dyn offchain::Externalities>),
/// Context used for other calls.
Other,
}
+4 -4
View File
@@ -35,8 +35,8 @@ impl TryFrom<u32> for CryptoKind {
fn try_from(kind: u32) -> Result<Self, Self::Error> {
match kind {
e if e == CryptoKind::Sr25519 as u8 as u32 => Ok(CryptoKind::Sr25519),
e if e == CryptoKind::Ed25519 as u8 as u32 => Ok(CryptoKind::Ed25519),
e if e == u32::from(CryptoKind::Sr25519 as u8) => Ok(CryptoKind::Sr25519),
e if e == u32::from(CryptoKind::Ed25519 as u8) => Ok(CryptoKind::Ed25519),
_ => Err(())
}
}
@@ -103,7 +103,7 @@ impl From<HttpRequestStatus> for u32 {
HttpRequestStatus::Unknown => 0,
HttpRequestStatus::DeadlineReached => 10,
HttpRequestStatus::Timeout => 20,
HttpRequestStatus::Finished(code) => code as u32,
HttpRequestStatus::Finished(code) => u32::from(code),
}
}
}
@@ -116,7 +116,7 @@ impl TryFrom<u32> for HttpRequestStatus {
0 => Ok(HttpRequestStatus::Unknown),
10 => Ok(HttpRequestStatus::DeadlineReached),
20 => Ok(HttpRequestStatus::Timeout),
100...999 => Ok(HttpRequestStatus::Finished(status as u16)),
100..=999 => u16::try_from(status).map(HttpRequestStatus::Finished).map_err(|_| ()),
_ => Err(()),
}
}
+8 -10
View File
@@ -204,16 +204,16 @@ impl From<schnorrkel::Signature> for Signature {
}
#[cfg(feature = "std")]
impl ::std::fmt::Debug for Signature {
impl std::fmt::Debug for Signature {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{}", crate::hexdisplay::HexDisplay::from(&self.0))
}
}
#[cfg(feature = "std")]
impl ::std::hash::Hash for Signature {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
::std::hash::Hash::hash(&self.0[..], state);
impl std::hash::Hash for Signature {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::hash::Hash::hash(&self.0[..], state);
}
}
@@ -304,15 +304,13 @@ impl Public {
/// Return a `Vec<u8>` filled with raw data.
#[cfg(feature = "std")]
pub fn to_raw_vec(self) -> Vec<u8> {
let r: &[u8; 32] = self.as_ref();
r.to_vec()
pub fn into_raw_vec(self) -> Vec<u8> {
self.0.to_vec()
}
/// Return a slice filled with raw data.
pub fn as_slice(&self) -> &[u8] {
let r: &[u8; 32] = self.as_ref();
&r[..]
&self.0
}
/// Return a slice filled with raw data.
@@ -637,7 +635,7 @@ mod test {
#[test]
fn verify_from_wasm_works() {
// The values in this test case are compared to the output of `node-test.js` in schnorrkel-js.
//
//
// This is to make sure that the wasm library is compatible.
let pk = Pair::from_seed(hex!("0000000000000000000000000000000000000000000000000000000000000000"));
let public = pk.public();
+1 -1
View File
@@ -34,7 +34,7 @@ pub enum Error {
Pool(txpool::error::Error),
/// Verification error
#[display(fmt="Extrinsic verification error: {}", "_0.description()")]
Verification(Box<::std::error::Error + Send>),
Verification(Box<dyn std::error::Error + Send>),
/// Incorrect extrinsic format.
#[display(fmt="Invalid extrinsic format")]
BadFormat,
+2 -2
View File
@@ -74,7 +74,7 @@ pub trait SystemApi<Hash, Number> {
/// System API implementation
pub struct System<B: traits::Block> {
info: SystemInfo,
sync: Arc<network::SyncProvider<B>>,
sync: Arc<dyn network::SyncProvider<B>>,
should_have_peers: bool,
}
@@ -82,7 +82,7 @@ impl<B: traits::Block> System<B> {
/// Creates new `System` given the `SystemInfo`.
pub fn new(
info: SystemInfo,
sync: Arc<network::SyncProvider<B>>,
sync: Arc<dyn network::SyncProvider<B>>,
should_have_peers: bool,
) -> Self {
System {
+1 -1
View File
@@ -151,7 +151,7 @@ pub fn import_blocks<F, E, R>(
let (header, extrinsics) = signed.block.deconstruct();
let hash = header.hash();
let block = message::BlockData::<F::Block> {
hash: hash,
hash,
justification: signed.justification,
header: Some(header),
body: Some(extrinsics),
+6 -6
View File
@@ -139,7 +139,7 @@ pub trait StartRPC<C: Components> {
fn start_rpc(
client: Arc<ComponentClient<C>>,
network: Arc<network::SyncProvider<ComponentBlock<C>>>,
network: Arc<dyn network::SyncProvider<ComponentBlock<C>>>,
should_have_peers: bool,
system_info: SystemInfo,
rpc_http: Option<SocketAddr>,
@@ -159,7 +159,7 @@ impl<C: Components> StartRPC<Self> for C where
fn start_rpc(
client: Arc<ComponentClient<C>>,
network: Arc<network::SyncProvider<ComponentBlock<C>>>,
network: Arc<dyn network::SyncProvider<ComponentBlock<C>>>,
should_have_peers: bool,
rpc_system_info: SystemInfo,
rpc_http: Option<SocketAddr>,
@@ -339,7 +339,7 @@ pub trait ServiceFactory: 'static + Sized {
/// Build finality proof provider for serving network requests on full node.
fn build_finality_proof_provider(
client: Arc<FullClient<Self>>
) -> Result<Option<Arc<FinalityProofProvider<Self::Block>>>, error::Error>;
) -> Result<Option<Arc<dyn FinalityProofProvider<Self::Block>>>, error::Error>;
/// Build the Fork Choice algorithm for full client
fn build_select_chain(
@@ -435,7 +435,7 @@ pub trait Components: Sized + 'static {
/// Finality proof provider for serving network requests.
fn build_finality_proof_provider(
client: Arc<ComponentClient<Self>>
) -> Result<Option<Arc<FinalityProofProvider<<Self::Factory as ServiceFactory>::Block>>>, error::Error>;
) -> Result<Option<Arc<dyn FinalityProofProvider<<Self::Factory as ServiceFactory>::Block>>>, error::Error>;
/// Build fork choice selector
fn build_select_chain(
@@ -536,7 +536,7 @@ impl<Factory: ServiceFactory> Components for FullComponents<Factory> {
fn build_finality_proof_provider(
client: Arc<ComponentClient<Self>>
) -> Result<Option<Arc<FinalityProofProvider<<Self::Factory as ServiceFactory>::Block>>>, error::Error> {
) -> Result<Option<Arc<dyn FinalityProofProvider<<Self::Factory as ServiceFactory>::Block>>>, error::Error> {
Factory::build_finality_proof_provider(client)
}
}
@@ -619,7 +619,7 @@ impl<Factory: ServiceFactory> Components for LightComponents<Factory> {
fn build_finality_proof_provider(
_client: Arc<ComponentClient<Self>>
) -> Result<Option<Arc<FinalityProofProvider<<Self::Factory as ServiceFactory>::Block>>>, error::Error> {
) -> Result<Option<Arc<dyn FinalityProofProvider<<Self::Factory as ServiceFactory>::Block>>>, error::Error> {
Ok(None)
}
fn build_select_chain(
+2 -2
View File
@@ -80,7 +80,7 @@ pub struct Service<Components: components::Components> {
signal: Option<Signal>,
/// Configuration of this Service
pub config: FactoryFullConfiguration<Components::Factory>,
_rpc: Box<::std::any::Any + Send + Sync>,
_rpc: Box<dyn std::any::Any + Send + Sync>,
_telemetry: Option<Arc<tel::Telemetry>>,
_offchain_workers: Option<Arc<offchain::OffchainWorkers<ComponentClient<Components>, ComponentBlock<Components>>>>,
_telemetry_on_connect_sinks: Arc<Mutex<Vec<mpsc::UnboundedSender<()>>>>,
@@ -104,7 +104,7 @@ pub type TelemetryOnConnectNotifications = mpsc::UnboundedReceiver<()>;
/// Used to hook on telemetry connection established events.
pub struct TelemetryOnConnect<'a> {
/// Handle to a future that will resolve on exit.
pub on_exit: Box<Future<Item=(), Error=()> + Send + 'static>,
pub on_exit: Box<dyn Future<Item=(), Error=()> + Send + 'static>,
/// Event stream.
pub telemetry_connection_sinks: TelemetryOnConnectNotifications,
/// Executor to which the hook is spawned.
+12 -3
View File
@@ -54,11 +54,11 @@ mod utils;
/// # extern crate substrate_primitives;
/// #
/// # use runtime_primitives::traits::GetNodeBlockType;
/// # use test_client::runtime::Block;
/// # use test_client::runtime::{Block, Header};
/// #
/// # /// The declaration of the `Runtime` type and the implementation of the `GetNodeBlockType`
/// # /// trait are done by the `construct_runtime!` macro in a real runtime.
/// # struct Runtime {}
/// # pub struct Runtime {}
/// # impl GetNodeBlockType for Runtime {
/// # type NodeBlock = Block;
/// # }
@@ -78,6 +78,15 @@ mod utils;
///
/// /// All runtime api implementations need to be done in one call of the macro!
/// impl_runtime_apis! {
/// # impl client::runtime_api::Core<Block> for Runtime {
/// # fn version() -> client::runtime_api::RuntimeVersion {
/// # unimplemented!()
/// # }
/// # fn execute_block(_block: Block) {}
/// # fn initialize_block(_header: &Header) {}
/// # fn authorities() -> Vec<runtime_primitives::traits::AuthorityIdFor<Block>> { unimplemented!() }
/// # }
///
/// impl self::Balance<Block> for Runtime {
/// fn get_balance() -> u64 {
/// 1
@@ -176,7 +185,7 @@ pub fn impl_runtime_apis(input: TokenStream) -> TokenStream {
/// ///
/// /// Is callable by `set_balance_before_version_2`.
/// #[changed_in(2)]
/// fn set_balance(val: u8);
/// fn set_balance(val: u16);
/// /// In version 2, we added this new function.
/// fn increase_balance(val: u64);
/// }
@@ -122,7 +122,7 @@ fn check_runtime_api_versions_contains<T: RuntimeApiInfo + ?Sized>() {
#[test]
fn check_runtime_api_versions() {
check_runtime_api_versions_contains::<Api<Block>>();
check_runtime_api_versions_contains::<ApiWithCustomVersion<Block>>();
check_runtime_api_versions_contains::<runtime_api::Core<Block>>();
check_runtime_api_versions_contains::<dyn Api<Block>>();
check_runtime_api_versions_contains::<dyn ApiWithCustomVersion<Block>>();
check_runtime_api_versions_contains::<dyn runtime_api::Core<Block>>();
}
+2 -2
View File
@@ -251,7 +251,7 @@ impl HashingApi for () {
}
}
fn with_offchain<R>(f: impl FnOnce(&mut offchain::Externalities) -> R, msg: &'static str) -> R {
fn with_offchain<R>(f: impl FnOnce(&mut dyn offchain::Externalities) -> R, msg: &'static str) -> R {
ext::with(|ext| ext
.offchain()
.map(|ext| f(ext))
@@ -395,7 +395,7 @@ impl Api for () {}
/// Execute the given closure with global function available whose functionality routes into the
/// externalities `ext`. Forwards the value that the closure returns.
// NOTE: need a concrete hasher here due to limitations of the `environmental!` macro, otherwise a type param would have been fine I think.
pub fn with_externalities<R, F: FnOnce() -> R>(ext: &mut Externalities<Blake2Hasher>, f: F) -> R {
pub fn with_externalities<R, F: FnOnce() -> R>(ext: &mut dyn Externalities<Blake2Hasher>, f: F) -> R {
ext::using(ext, f)
}
@@ -44,8 +44,8 @@ use rstd::prelude::*;
fn encode_with_vec_prefix<T: Encode, F: Fn(&mut Vec<u8>)>(encoder: F) -> Vec<u8> {
let size = ::rstd::mem::size_of::<T>();
let reserve = match size {
0...0b00111111 => 1,
0...0b00111111_11111111 => 2,
0..=0b00111111 => 1,
0..=0b00111111_11111111 => 2,
_ => 4,
};
let mut v = Vec::with_capacity(reserve + size);
+3 -3
View File
@@ -156,7 +156,7 @@ impl<H: Hasher> Externalities<H> for BasicExternalities where H::Out: Ord {
Ok(None)
}
fn offchain(&mut self) -> Option<&mut offchain::Externalities> {
fn offchain(&mut self) -> Option<&mut dyn offchain::Externalities> {
warn!("Call to non-existent out offchain externalities set.");
None
}
@@ -171,7 +171,7 @@ mod tests {
#[test]
fn commit_should_work() {
let mut ext = BasicExternalities::default();
let ext = &mut ext as &mut Externalities<Blake2Hasher>;
let ext = &mut ext as &mut dyn Externalities<Blake2Hasher>;
ext.set_storage(b"doe".to_vec(), b"reindeer".to_vec());
ext.set_storage(b"dog".to_vec(), b"puppy".to_vec());
ext.set_storage(b"dogglesworth".to_vec(), b"cat".to_vec());
@@ -182,7 +182,7 @@ mod tests {
#[test]
fn set_and_retrieve_code() {
let mut ext = BasicExternalities::default();
let ext = &mut ext as &mut Externalities<Blake2Hasher>;
let ext = &mut ext as &mut dyn Externalities<Blake2Hasher>;
let code = vec![1, 2, 3];
ext.set_storage(CODE.to_vec(), code.clone());
@@ -112,7 +112,7 @@ pub trait Storage<H: Hasher, Number: BlockNumber>: RootsStorage<H, Number> {
}
/// Changes trie storage -> trie backend essence adapter.
pub struct TrieBackendStorageAdapter<'a, H: Hasher, Number: BlockNumber>(pub &'a Storage<H, Number>);
pub struct TrieBackendStorageAdapter<'a, H: Hasher, Number: BlockNumber>(pub &'a dyn Storage<H, Number>);
impl<'a, H: Hasher, N: BlockNumber> crate::TrieBackendStorage<H> for TrieBackendStorageAdapter<'a, H, N> {
type Overlay = trie::MemoryDB<H>;
+1 -1
View File
@@ -343,7 +343,7 @@ where
Ok(root)
}
fn offchain(&mut self) -> Option<&mut offchain::Externalities> {
fn offchain(&mut self) -> Option<&mut dyn offchain::Externalities> {
self.offchain_externalities.as_mut().map(|x| &mut **x as _)
}
}
+32 -29
View File
@@ -222,7 +222,7 @@ pub trait Externalities<H: Hasher> {
fn storage_changes_root(&mut self, parent: H::Out) -> Result<Option<H::Out>, ()> where H::Out: Ord;
/// Returns offchain externalities extension if present.
fn offchain(&mut self) -> Option<&mut offchain::Externalities>;
fn offchain(&mut self) -> Option<&mut dyn offchain::Externalities>;
}
/// An implementation of offchain extensions that should never be triggered.
@@ -502,7 +502,7 @@ impl<'a, H, N, B, T, O, Exec> StateMachine<'a, H, N, B, T, O, Exec> where
pub fn execute(
&mut self,
strategy: ExecutionStrategy,
) -> Result<(Vec<u8>, B::Transaction, Option<MemoryDB<H>>), Box<Error>> {
) -> Result<(Vec<u8>, B::Transaction, Option<MemoryDB<H>>), Box<dyn Error>> {
// We are not giving a native call and thus we are sure that the result can never be a native
// value.
self.execute_using_consensus_failure_handler::<_, NeverNativeValue, fn() -> _>(
@@ -613,7 +613,7 @@ impl<'a, H, N, B, T, O, Exec> StateMachine<'a, H, N, B, T, O, Exec> where
manager: ExecutionManager<Handler>,
compute_tx: bool,
mut native_call: Option<NC>,
) -> Result<(NativeOrEncoded<R>, Option<B::Transaction>, Option<MemoryDB<H>>), Box<Error>> where
) -> Result<(NativeOrEncoded<R>, Option<B::Transaction>, Option<MemoryDB<H>>), Box<dyn Error>> where
R: Decode + Encode + PartialEq,
NC: FnOnce() -> result::Result<R, &'static str> + UnwindSafe,
Handler: FnOnce(
@@ -674,7 +674,7 @@ pub fn prove_execution<B, H, Exec>(
exec: &Exec,
method: &str,
call_data: &[u8],
) -> Result<(Vec<u8>, Vec<Vec<u8>>), Box<Error>>
) -> Result<(Vec<u8>, Vec<Vec<u8>>), Box<dyn Error>>
where
B: Backend<H>,
H: Hasher,
@@ -682,7 +682,7 @@ where
H::Out: Ord + 'static,
{
let trie_backend = backend.as_trie_backend()
.ok_or_else(|| Box::new(ExecutionError::UnableToGenerateProof) as Box<Error>)?;
.ok_or_else(|| Box::new(ExecutionError::UnableToGenerateProof) as Box<dyn Error>)?;
prove_execution_on_trie_backend(trie_backend, overlay, exec, method, call_data)
}
@@ -701,7 +701,7 @@ pub fn prove_execution_on_trie_backend<S, H, Exec>(
exec: &Exec,
method: &str,
call_data: &[u8],
) -> Result<(Vec<u8>, Vec<Vec<u8>>), Box<Error>>
) -> Result<(Vec<u8>, Vec<Vec<u8>>), Box<dyn Error>>
where
S: trie_backend_essence::TrieBackendStorage<H>,
H: Hasher,
@@ -736,7 +736,7 @@ pub fn execution_proof_check<H, Exec>(
exec: &Exec,
method: &str,
call_data: &[u8],
) -> Result<Vec<u8>, Box<Error>>
) -> Result<Vec<u8>, Box<dyn Error>>
where
H: Hasher,
Exec: CodeExecutor<H>,
@@ -753,7 +753,7 @@ pub fn execution_proof_check_on_trie_backend<H, Exec>(
exec: &Exec,
method: &str,
call_data: &[u8],
) -> Result<Vec<u8>, Box<Error>>
) -> Result<Vec<u8>, Box<dyn Error>>
where
H: Hasher,
Exec: CodeExecutor<H>,
@@ -780,7 +780,7 @@ where
pub fn prove_read<B, H>(
mut backend: B,
key: &[u8]
) -> Result<(Option<Vec<u8>>, Vec<Vec<u8>>), Box<Error>>
) -> Result<(Option<Vec<u8>>, Vec<Vec<u8>>), Box<dyn Error>>
where
B: Backend<H>,
H: Hasher,
@@ -788,7 +788,7 @@ where
{
let trie_backend = backend.as_trie_backend()
.ok_or_else(
||Box::new(ExecutionError::UnableToGenerateProof) as Box<Error>
||Box::new(ExecutionError::UnableToGenerateProof) as Box<dyn Error>
)?;
prove_read_on_trie_backend(trie_backend, key)
}
@@ -798,14 +798,14 @@ pub fn prove_child_read<B, H>(
mut backend: B,
storage_key: &[u8],
key: &[u8],
) -> Result<(Option<Vec<u8>>, Vec<Vec<u8>>), Box<Error>>
) -> Result<(Option<Vec<u8>>, Vec<Vec<u8>>), Box<dyn Error>>
where
B: Backend<H>,
H: Hasher,
H::Out: Ord
{
let trie_backend = backend.as_trie_backend()
.ok_or_else(|| Box::new(ExecutionError::UnableToGenerateProof) as Box<Error>)?;
.ok_or_else(|| Box::new(ExecutionError::UnableToGenerateProof) as Box<dyn Error>)?;
prove_child_read_on_trie_backend(trie_backend, storage_key, key)
}
@@ -814,14 +814,14 @@ where
pub fn prove_read_on_trie_backend<S, H>(
trie_backend: &TrieBackend<S, H>,
key: &[u8]
) -> Result<(Option<Vec<u8>>, Vec<Vec<u8>>), Box<Error>>
) -> Result<(Option<Vec<u8>>, Vec<Vec<u8>>), Box<dyn Error>>
where
S: trie_backend_essence::TrieBackendStorage<H>,
H: Hasher,
H::Out: Ord
{
let proving_backend = proving_backend::ProvingBackend::<_, H>::new(trie_backend);
let result = proving_backend.storage(key).map_err(|e| Box::new(e) as Box<Error>)?;
let result = proving_backend.storage(key).map_err(|e| Box::new(e) as Box<dyn Error>)?;
Ok((result, proving_backend.extract_proof()))
}
@@ -830,15 +830,14 @@ pub fn prove_child_read_on_trie_backend<S, H>(
trie_backend: &TrieBackend<S, H>,
storage_key: &[u8],
key: &[u8]
) -> Result<(Option<Vec<u8>>, Vec<Vec<u8>>), Box<Error>>
) -> Result<(Option<Vec<u8>>, Vec<Vec<u8>>), Box<dyn Error>>
where
S: trie_backend_essence::TrieBackendStorage<H>,
H: Hasher,
H::Out: Ord
{
let proving_backend = proving_backend::ProvingBackend::<_, H>::new(trie_backend);
let result = proving_backend.child_storage(storage_key, key)
.map_err(|e| Box::new(e) as Box<Error>)?;
let result = proving_backend.child_storage(storage_key, key).map_err(|e| Box::new(e) as Box<dyn Error>)?;
Ok((result, proving_backend.extract_proof()))
}
@@ -847,7 +846,7 @@ pub fn read_proof_check<H>(
root: H::Out,
proof: Vec<Vec<u8>>,
key: &[u8],
) -> Result<Option<Vec<u8>>, Box<Error>>
) -> Result<Option<Vec<u8>>, Box<dyn Error>>
where
H: Hasher,
H::Out: Ord
@@ -862,7 +861,7 @@ pub fn read_child_proof_check<H>(
proof: Vec<Vec<u8>>,
storage_key: &[u8],
key: &[u8],
) -> Result<Option<Vec<u8>>, Box<Error>>
) -> Result<Option<Vec<u8>>, Box<dyn Error>>
where
H: Hasher,
H::Out: Ord
@@ -876,12 +875,12 @@ where
pub fn read_proof_check_on_proving_backend<H>(
proving_backend: &TrieBackend<MemoryDB<H>, H>,
key: &[u8],
) -> Result<Option<Vec<u8>>, Box<Error>>
) -> Result<Option<Vec<u8>>, Box<dyn Error>>
where
H: Hasher,
H::Out: Ord
{
proving_backend.storage(key).map_err(|e| Box::new(e) as Box<Error>)
proving_backend.storage(key).map_err(|e| Box::new(e) as Box<dyn Error>)
}
/// Check child storage read proof on pre-created proving backend.
@@ -889,20 +888,24 @@ pub fn read_child_proof_check_on_proving_backend<H>(
proving_backend: &TrieBackend<MemoryDB<H>, H>,
storage_key: &[u8],
key: &[u8],
) -> Result<Option<Vec<u8>>, Box<Error>>
) -> Result<Option<Vec<u8>>, Box<dyn Error>>
where
H: Hasher,
H::Out: Ord
{
proving_backend.child_storage(storage_key, key).map_err(|e| Box::new(e) as Box<Error>)
proving_backend.child_storage(storage_key, key).map_err(|e| Box::new(e) as Box<dyn Error>)
}
/// Sets overlayed changes' changes trie configuration. Returns error if configuration
/// differs from previous OR config decode has failed.
pub(crate) fn set_changes_trie_config(overlay: &mut OverlayedChanges, config: Option<Vec<u8>>, final_check: bool) -> Result<(), Box<Error>> {
pub(crate) fn set_changes_trie_config(
overlay: &mut OverlayedChanges,
config: Option<Vec<u8>>,
final_check: bool,
) -> Result<(), Box<dyn Error>> {
let config = match config {
Some(v) => Some(Decode::decode(&mut &v[..])
.ok_or_else(|| Box::new("Failed to decode changes trie configuration".to_owned()) as Box<Error>)?),
.ok_or_else(|| Box::new("Failed to decode changes trie configuration".to_owned()) as Box<dyn Error>)?),
None => None,
};
@@ -920,16 +923,16 @@ pub(crate) fn set_changes_trie_config(overlay: &mut OverlayedChanges, config: Op
/// Reads storage value from overlay or from the backend.
fn try_read_overlay_value<H, B>(overlay: &OverlayedChanges, backend: &B, key: &[u8])
-> Result<Option<Vec<u8>>, Box<Error>>
-> Result<Option<Vec<u8>>, Box<dyn Error>>
where
H: Hasher,
B: Backend<H>,
{
match overlay.storage(key).map(|x| x.map(|x| x.to_vec())) {
Some(value) => Ok(value),
None => backend.storage(key)
.map_err(|err| Box::new(ExecutionError::Backend(format!("{}", err))) as Box<Error>),
None => backend
.storage(key)
.map_err(|err| Box::new(ExecutionError::Backend(format!("{}", err))) as Box<dyn Error>),
}
}
@@ -193,17 +193,17 @@ impl<'a, S, H> Backend<H> for ProvingBackend<'a, S, H>
pub fn create_proof_check_backend<H>(
root: H::Out,
proof: Vec<Vec<u8>>
) -> Result<TrieBackend<MemoryDB<H>, H>, Box<Error>>
) -> Result<TrieBackend<MemoryDB<H>, H>, Box<dyn Error>>
where
H: Hasher,
{
let db = create_proof_check_backend_storage(proof);
if !db.contains(&root, &[]) {
return Err(Box::new(ExecutionError::InvalidProof) as Box<Error>);
if db.contains(&root, &[]) {
Ok(TrieBackend::new(db, root))
} else {
Err(Box::new(ExecutionError::InvalidProof))
}
Ok(TrieBackend::new(db, root))
}
/// Create in-memory storage of proof check backend.
+2 -2
View File
@@ -37,7 +37,7 @@ pub struct TestExternalities<H: Hasher, N: ChangesTrieBlockNumber> {
overlay: OverlayedChanges,
backend: InMemory<H>,
changes_trie_storage: ChangesTrieInMemoryStorage<H, N>,
offchain: Option<Box<offchain::Externalities>>,
offchain: Option<Box<dyn offchain::Externalities>>,
}
impl<H: Hasher, N: ChangesTrieBlockNumber> TestExternalities<H, N> {
@@ -234,7 +234,7 @@ impl<H, N> Externalities<H> for TestExternalities<H, N>
)?.map(|(root, _)| root.clone()))
}
fn offchain(&mut self) -> Option<&mut offchain::Externalities> {
fn offchain(&mut self) -> Option<&mut dyn offchain::Externalities> {
self.offchain
.as_mut()
.map(|x| &mut **x as _)
@@ -153,8 +153,8 @@ impl<'a,
> hash_db::AsPlainDB<H::Out, DBValue>
for Ephemeral<'a, S, H>
{
fn as_plain_db<'b>(&'b self) -> &'b (hash_db::PlainDB<H::Out, DBValue> + 'b) { self }
fn as_plain_db_mut<'b>(&'b mut self) -> &'b mut (hash_db::PlainDB<H::Out, DBValue> + 'b) { self }
fn as_plain_db<'b>(&'b self) -> &'b (dyn hash_db::PlainDB<H::Out, DBValue> + 'b) { self }
fn as_plain_db_mut<'b>(&'b mut self) -> &'b mut (dyn hash_db::PlainDB<H::Out, DBValue> + 'b) { self }
}
impl<'a,
@@ -163,8 +163,8 @@ impl<'a,
> hash_db::AsHashDB<H, DBValue>
for Ephemeral<'a, S, H>
{
fn as_hash_db<'b>(&'b self) -> &'b (hash_db::HashDB<H, DBValue> + 'b) { self }
fn as_hash_db_mut<'b>(&'b mut self) -> &'b mut (hash_db::HashDB<H, DBValue> + 'b) { self }
fn as_hash_db<'b>(&'b self) -> &'b (dyn hash_db::HashDB<H, DBValue> + 'b) { self }
fn as_hash_db_mut<'b>(&'b mut self) -> &'b mut (dyn hash_db::HashDB<H, DBValue> + 'b) { self }
}
impl<'a, S: TrieBackendStorage<H>, H: Hasher> Ephemeral<'a, S, H> {
@@ -275,7 +275,7 @@ pub trait TrieBackendStorage<H: Hasher>: Send + Sync {
}
// This implementation is used by normal storage trie clients.
impl<H: Hasher> TrieBackendStorage<H> for Arc<Storage<H>> {
impl<H: Hasher> TrieBackendStorage<H> for Arc<dyn Storage<H>> {
type Overlay = PrefixedMemoryDB<H>;
fn get(&self, key: &H::Out, prefix: &[u8]) -> Result<Option<DBValue>, String> {
+5 -5
View File
@@ -38,14 +38,14 @@ pub struct TelemetryConfig {
pub endpoints: TelemetryEndpoints,
/// What do do when we connect to the servers.
/// Note that this closure is executed each time we connect to a telemetry endpoint.
pub on_connect: Box<Fn() + Send + Sync + 'static>,
pub on_connect: Box<dyn Fn() + Send + Sync + 'static>,
}
/// Telemetry service guard.
pub type Telemetry = slog_scope::GlobalLoggerGuard;
/// Size of the channel for passing messages to telemetry thread.
const CHANNEL_SIZE: usize = 262144;
const CHANNEL_SIZE: usize = 262_144;
/// Log levels.
pub const SUBSTRATE_DEBUG: &str = "9";
@@ -154,7 +154,7 @@ pub fn init_telemetry(config: TelemetryConfig) -> slog_scope::GlobalLoggerGuard
});
});
return logger_guard;
logger_guard
}
/// Translates to `slog_scope::info`, but contains an additional verbosity
@@ -172,7 +172,7 @@ macro_rules! telemetry {
struct Connection {
out: ws::Sender,
out_sync: Arc<Mutex<Option<ws::Sender>>>,
on_connect: Arc<Box<Fn() + Send + Sync + 'static>>,
on_connect: Arc<Box<dyn Fn() + Send + Sync + 'static>>,
url: String,
}
@@ -180,7 +180,7 @@ impl Connection {
fn new(
out: ws::Sender,
out_sync: Arc<Mutex<Option<ws::Sender>>>,
on_connect: Arc<Box<Fn() + Send + Sync + 'static>>,
on_connect: Arc<Box<dyn Fn() + Send + Sync + 'static>>,
url: String
) -> Self {
Connection {
@@ -35,7 +35,7 @@ pub enum Error {
TemporarilyBanned,
/// The transaction is already in the pool.
#[display(fmt="[{:?}] Already imported", _0)]
AlreadyImported(Box<std::any::Any + Send>),
AlreadyImported(Box<dyn std::any::Any + Send>),
/// The transaction cannot be imported cause it's a replacement and has too low priority.
#[display(fmt="Too low priority ({} > {})", old, new)]
TooLowPriority {
+3 -3
View File
@@ -43,9 +43,9 @@ pub type TrieError<H> = trie_db::TrieError<H, Error>;
pub trait AsHashDB<H: Hasher>: hash_db::AsHashDB<H, trie_db::DBValue> {}
impl<H: Hasher, T: hash_db::AsHashDB<H, trie_db::DBValue>> AsHashDB<H> for T {}
/// As in `hash_db`, but less generic, trait exposed.
pub type HashDB<'a, H> = hash_db::HashDB<H, trie_db::DBValue> + 'a;
pub type HashDB<'a, H> = dyn hash_db::HashDB<H, trie_db::DBValue> + 'a;
/// As in `hash_db`, but less generic, trait exposed.
pub type PlainDB<'a, K> = hash_db::PlainDB<K, trie_db::DBValue> + 'a;
pub type PlainDB<'a, K> = dyn hash_db::PlainDB<K, trie_db::DBValue> + 'a;
/// As in `memory_db::MemoryDB` that uses prefixed storage key scheme.
pub type PrefixedMemoryDB<H> = memory_db::MemoryDB<H, memory_db::PrefixedKey<H>, trie_db::DBValue>;
/// As in `memory_db::MemoryDB` that uses prefixed storage key scheme.
@@ -471,7 +471,7 @@ mod tests {
}
fn populate_trie<'db>(
db: &'db mut HashDB<Blake2Hasher, DBValue>,
db: &'db mut dyn HashDB<Blake2Hasher, DBValue>,
root: &'db mut <Blake2Hasher as Hasher>::Out,
v: &[(Vec<u8>, Vec<u8>)]
) -> TrieDBMut<'db, Blake2Hasher> {
+2 -2
View File
@@ -60,12 +60,12 @@ impl Decode for NodeHeader {
Some(match input.read_byte()? {
EMPTY_TRIE => NodeHeader::Null, // 0
i @ LEAF_NODE_OFFSET ... LEAF_NODE_SMALL_MAX => // 1 ... (127 - 1)
i @ LEAF_NODE_OFFSET ..= LEAF_NODE_SMALL_MAX => // 1 ... (127 - 1)
NodeHeader::Leaf((i - LEAF_NODE_OFFSET) as usize),
LEAF_NODE_BIG => // 127
NodeHeader::Leaf(input.read_byte()? as usize + LEAF_NODE_THRESHOLD as usize),
i @ EXTENSION_NODE_OFFSET ... EXTENSION_NODE_SMALL_MAX =>// 128 ... (253 - 1)
i @ EXTENSION_NODE_OFFSET ..= EXTENSION_NODE_SMALL_MAX =>// 128 ... (253 - 1)
NodeHeader::Extension((i - EXTENSION_NODE_OFFSET) as usize),
EXTENSION_NODE_BIG => // 253
NodeHeader::Extension(input.read_byte()? as usize + EXTENSION_NODE_THRESHOLD as usize),
+2 -2
View File
@@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! `TrieStream` implementation for Substrate's trie format.
//! `TrieStream` implementation for Substrate's trie format.
use rstd::iter::once;
use hash_db::Hasher;
@@ -83,7 +83,7 @@ impl trie_root::TrieStream for TrieStream {
fn append_substream<H: Hasher>(&mut self, other: Self) {
let data = other.out();
match data.len() {
0...31 => {
0..=31 => {
data.encode_to(&mut self.buffer)
},
_ => {
+1 -1
View File
@@ -52,7 +52,7 @@ impl<E: std::error::Error> std::error::Error for Error<E> {
}
}
fn cause(&self) -> Option<&std::error::Error> {
fn cause(&self) -> Option<&dyn std::error::Error> {
None
}
}
-1
View File
@@ -150,7 +150,6 @@ impl ProvideInherentData for InherentDataProvider {
}
fn error_to_string(&self, error: &[u8]) -> Option<String> {
use parity_codec::Decode;
RuntimeString::decode(&mut &error[..]).map(Into::into)
}
}
+1 -1
View File
@@ -703,7 +703,7 @@ mod tests {
}
#[derive(Clone)]
struct MockExecutable<'a>(Rc<Fn(MockCtx) -> VmExecResult + 'a>);
struct MockExecutable<'a>(Rc<dyn Fn(MockCtx) -> VmExecResult + 'a>);
impl<'a> MockExecutable<'a> {
fn new(f: impl Fn(MockCtx) -> VmExecResult + 'a) -> Self {
+4 -4
View File
@@ -300,15 +300,15 @@ fn account_removal_removes_storage() {
// Verify that all entries from account 1 is removed, while
// entries from account 2 is in place.
{
assert!(<AccountDb<Test>>::get_storage(&DirectAccountDb, &1, Some(&trie_id1), key1).is_none());
assert!(<AccountDb<Test>>::get_storage(&DirectAccountDb, &1, Some(&trie_id1), key2).is_none());
assert!(<dyn AccountDb<Test>>::get_storage(&DirectAccountDb, &1, Some(&trie_id1), key1).is_none());
assert!(<dyn AccountDb<Test>>::get_storage(&DirectAccountDb, &1, Some(&trie_id1), key2).is_none());
assert_eq!(
<AccountDb<Test>>::get_storage(&DirectAccountDb, &2, Some(&trie_id2), key1),
<dyn AccountDb<Test>>::get_storage(&DirectAccountDb, &2, Some(&trie_id2), key1),
Some(b"3".to_vec())
);
assert_eq!(
<AccountDb<Test>>::get_storage(&DirectAccountDb, &2, Some(&trie_id2), key2),
<dyn AccountDb<Test>>::get_storage(&DirectAccountDb, &2, Some(&trie_id2), key2),
Some(b"4".to_vec())
);
}
+1 -1
View File
@@ -64,7 +64,7 @@ impl<AccountId, AccountIndex> Decode for Address<AccountId, AccountIndex> where
{
fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(match input.read_byte()? {
x @ 0x00...0xef => Address::Index(AccountIndex::from(x as u32)),
x @ 0x00..=0xef => Address::Index(AccountIndex::from(x as u32)),
0xfc => Address::Index(AccountIndex::from(
need_more_than(0xef, u16::decode(input)?)? as u32
)),
+3 -3
View File
@@ -19,9 +19,9 @@ use super::Crypto;
fn good_waypoint(done: u64) -> u64 {
match done {
0 ... 1_000_000 => 100_000,
0 ... 10_000_000 => 1_000_000,
0 ... 100_000_000 => 10_000_000,
0 ..= 1_000_000 => 100_000,
0 ..= 10_000_000 => 1_000_000,
0 ..= 100_000_000 => 10_000_000,
_ => 100_000_000,
}
}