diff --git a/substrate/core/basic-authorship/src/basic_authorship.rs b/substrate/core/basic-authorship/src/basic_authorship.rs index 87d0b8f92b..166a89447e 100644 --- a/substrate/core/basic-authorship/src/basic_authorship.rs +++ b/substrate/core/basic-authorship/src/basic_authorship.rs @@ -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) -> ()>( + fn build_block) -> ()>( &self, at: &BlockId, inherent_data: InherentData, @@ -91,7 +91,7 @@ impl AuthoringApi for SubstrateClient where type Block = Block; type Error = client::error::Error; - fn build_block) -> ()>( + fn build_block) -> ()>( &self, at: &BlockId, inherent_data: InherentData, @@ -162,7 +162,7 @@ pub struct Proposer { parent_id: BlockId, parent_number: <::Header as HeaderT>::Number, transaction_pool: Arc>, - now: Box time::Instant>, + now: Box time::Instant>, } impl consensus_common::Proposer<::Block> for Proposer where diff --git a/substrate/core/cli/src/lib.rs b/substrate/core/cli/src/lib.rs index 3619e6491a..c14c962591 100644 --- a/substrate/core/cli/src/lib.rs +++ b/substrate/core/cli/src/lib.rs @@ -617,7 +617,7 @@ where let to = cli.to; let json = cli.json; - let file: Box = match cli.output { + let file: Box = 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::(spec_factory, &cli.shared_params, version)?; - let file: Box = match cli.input { + let file: Box = match cli.input { Some(filename) => Box::new(File::open(filename)?), None => Box::new(stdin()), }; diff --git a/substrate/core/cli/src/params.rs b/substrate/core/cli/src/params.rs index 7439cc02c0..0cdc633188 100644 --- a/substrate/core/cli/src/params.rs +++ b/substrate/core/cli/src/params.rs @@ -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> { +fn parse_telemetry_endpoints(s: &str) -> Result<(String, u8), Box> { let pos = s.find(' '); match pos { None => { @@ -512,7 +512,7 @@ impl From for Option> { } /// Parse cors origins -fn parse_cors(s: &str) -> Result> { +fn parse_cors(s: &str) -> Result> { let mut is_all = false; let mut origins = Vec::new(); for part in s.split(',') { diff --git a/substrate/core/client/db/src/cache/list_storage.rs b/substrate/core/client/db/src/cache/list_storage.rs index 6271f892bc..af0b74066c 100644 --- a/substrate/core/client/db/src/cache/list_storage.rs +++ b/substrate/core/client/db/src/cache/list_storage.rs @@ -97,19 +97,19 @@ pub struct DbColumns { pub struct DbStorage { name: Vec, meta_key: Vec, - db: Arc, + db: Arc, columns: DbColumns, } impl DbStorage { /// Create new database-backed list cache storage. - pub fn new(name: Vec, db: Arc, columns: DbColumns) -> Self { + pub fn new(name: Vec, db: Arc, 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 { &self.db } + pub fn db(&self) -> &Arc { &self.db } /// Get reference to the database columns. pub fn columns(&self) -> &DbColumns { &self.columns } diff --git a/substrate/core/client/db/src/cache/mod.rs b/substrate/core/client/db/src/cache/mod.rs index d79b01ab6b..64d3c4a25e 100644 --- a/substrate/core/client/db/src/cache/mod.rs +++ b/substrate/core/client/db/src/cache/mod.rs @@ -77,7 +77,7 @@ impl CacheItemT for T where T: Clone + Decode + Encode + PartialEq {} /// Database-backed blockchain data cache. pub struct DbCache { cache_at: HashMap, self::list_storage::DbStorage>>, - db: Arc, + db: Arc, key_lookup_column: Option, header_column: Option, authorities_column: Option, @@ -88,7 +88,7 @@ pub struct DbCache { impl DbCache { /// Create new cache. pub fn new( - db: Arc, + db: Arc, key_lookup_column: Option, header_column: Option, authorities_column: Option, @@ -150,7 +150,7 @@ impl DbCache { fn get_cache_helper<'a, Block: BlockT>( cache_at: &'a mut HashMap, self::list_storage::DbStorage>>, name: CacheKeyId, - db: &Arc, + db: &Arc, key_lookup: Option, header: Option, cache: Option, diff --git a/substrate/core/client/db/src/lib.rs b/substrate/core/client/db/src/lib.rs index a253cc6783..302cdfd083 100644 --- a/substrate/core/client/db/src/lib.rs +++ b/substrate/core/client/db/src/lib.rs @@ -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>, Blake2Hasher>; +pub type DbState = state_machine::TrieBackend>, Blake2Hasher>; pub struct RefTrackingState { state: DbState, @@ -213,7 +213,7 @@ struct PendingBlock { } // 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 { - db: Arc, + db: Arc, meta: Arc, Block::Hash>>>, leaves: RwLock>>, } impl BlockchainDb { - fn new(db: Arc) -> Result { + fn new(db: Arc) -> Result { let meta = read_meta::(&*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 client::blockchain::Backend for BlockchainDb { Ok(self.meta.read().finalized_hash.clone()) } - fn cache(&self) -> Option>> { + fn cache(&self) -> Option>> { None } @@ -354,7 +354,7 @@ impl client::blockchain::Backend for BlockchainDb { } impl client::blockchain::ProvideCache for BlockchainDb { - fn cache(&self) -> Option>> { + fn cache(&self) -> Option>> { None } } @@ -473,7 +473,7 @@ where Block: BlockT, } struct StorageDb { - pub db: Arc, + pub db: Arc, pub state_db: StateDb>, } @@ -512,7 +512,7 @@ impl state_machine::Storage for DbGenesisStorage { } pub struct DbChangesTrieStorage { - db: Arc, + db: Arc, meta: Arc, Block::Hash>>>, min_blocks_to_keep: Option, _phantom: ::std::marker::PhantomData, @@ -693,7 +693,12 @@ impl> Backend { ).expect("failed to create test-db") } - fn from_kvdb(db: Arc, pruning: PruningMode, canonicalization_delay: u64, state_cache_size: usize) -> Result { + fn from_kvdb( + db: Arc, + pruning: PruningMode, + canonicalization_delay: u64, + state_cache_size: usize + ) -> Result { let is_archive_pruning = pruning.is_archive(); let blockchain = BlockchainDb::new(db.clone())?; let meta = blockchain.meta.clone(); diff --git a/substrate/core/client/db/src/light.rs b/substrate/core/client/db/src/light.rs index e0f2153a13..b3398bfdff 100644 --- a/substrate/core/client/db/src/light.rs +++ b/substrate/core/client/db/src/light.rs @@ -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 { - db: Arc, + db: Arc, meta: RwLock, Block::Hash>>, leaves: RwLock>>, cache: Arc>, @@ -96,7 +96,7 @@ impl LightStorage Self::from_kvdb(db as Arc<_>).expect("failed to create test-db") } - fn from_kvdb(db: Arc) -> ClientResult { + fn from_kvdb(db: Arc) -> ClientResult { let meta = read_meta::(&*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 LightBlockchainStorage for LightStorage Ok(self.meta.read().finalized_hash.clone()) } - fn cache(&self) -> Option>> { + fn cache(&self) -> Option>> { Some(self.cache.clone()) } } @@ -888,7 +888,7 @@ pub(crate) mod tests { map } - fn get_authorities(cache: &BlockchainCache, at: BlockId) -> Option> { + fn get_authorities(cache: &dyn BlockchainCache, at: BlockId) -> Option> { cache.get_at(&well_known_cache_keys::AUTHORITIES, &at).and_then(|val| Decode::decode(&mut &val[..])) } diff --git a/substrate/core/client/db/src/utils.rs b/substrate/core/client/db/src/utils.rs index 846bf05f3c..bd7cf660ea 100644 --- a/substrate/core/client/db/src/utils.rs +++ b/substrate/core/client/db/src/utils.rs @@ -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, 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( - db: &KeyValueDB, + db: &dyn KeyValueDB, key_lookup_col: Option, id: BlockId ) -> Result>, 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, db_type: &str) -> client::error::Result> { +pub fn open_database( + config: &DatabaseSettings, + col_meta: Option, + db_type: &str +) -> client::error::Result> { 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, db_type: } /// Read database column entry for the given block. -pub fn read_db(db: &KeyValueDB, col_index: Option, col: Option, id: BlockId) -> client::error::Result> +pub fn read_db( + db: &dyn KeyValueDB, + col_index: Option, + col: Option, + id: BlockId +) -> client::error::Result> where Block: BlockT, { @@ -234,7 +241,7 @@ pub fn read_db(db: &KeyValueDB, col_index: Option, col: Option, /// Read a header from the database. pub fn read_header( - db: &KeyValueDB, + db: &dyn KeyValueDB, col_index: Option, col: Option, id: BlockId, @@ -252,7 +259,7 @@ pub fn read_header( /// Required header from the database. pub fn require_header( - db: &KeyValueDB, + db: &dyn KeyValueDB, col_index: Option, col: Option, id: BlockId, @@ -262,7 +269,7 @@ pub fn require_header( } /// Read meta from the database. -pub fn read_meta(db: &KeyValueDB, col_meta: Option, col_header: Option) -> Result< +pub fn read_meta(db: &dyn KeyValueDB, col_meta: Option, col_header: Option) -> Result< Meta<<::Header as HeaderT>::Number, Block::Hash>, client::error::Error, > diff --git a/substrate/core/client/src/blockchain.rs b/substrate/core/client/src/blockchain.rs index 05210fc9ad..b07e26396e 100644 --- a/substrate/core/client/src/blockchain.rs +++ b/substrate/core/client/src/blockchain.rs @@ -81,7 +81,7 @@ pub trait Backend: HeaderBackend { /// Get last finalized block hash. fn last_finalized(&self) -> Result; /// Returns data cache reference, if it is enabled on this backend. - fn cache(&self) -> Option>>; + fn cache(&self) -> Option>>; /// 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: HeaderBackend { /// Provides access to the optional cache. pub trait ProvideCache { /// Returns data cache reference, if it is enabled on this backend. - fn cache(&self) -> Option>>; + fn cache(&self) -> Option>>; } /// Blockchain optional data cache. diff --git a/substrate/core/client/src/call_executor.rs b/substrate/core/client/src/call_executor.rs index bb59be44c3..f956f27b50 100644 --- a/substrate/core/client/src/call_executor.rs +++ b/substrate/core/client/src/call_executor.rs @@ -125,7 +125,7 @@ where let trie_state = state.as_trie_backend() .ok_or_else(|| Box::new(state_machine::ExecutionError::UnableToGenerateProof) - as Box + as Box )?; 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 + as Box )?; let backend = state_machine::ProvingBackend::new_with_recorder( diff --git a/substrate/core/client/src/children.rs b/substrate/core/client/src/children.rs index 3a9f0a6bea..4423ad8939 100644 --- a/substrate/core/client/src/children.rs +++ b/substrate/core/client/src/children.rs @@ -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, prefix: &[u8], parent_hash: K) -> error::Result> { +>(db: &dyn KeyValueDB, column: Option, prefix: &[u8], parent_hash: K) -> error::Result> { let mut buf = prefix.to_vec(); parent_hash.using_encoded(|s| buf.extend(s)); @@ -116,6 +116,6 @@ mod tests { let r2: Vec = 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); } } diff --git a/substrate/core/client/src/client.rs b/substrate/core/client/src/client.rs index 0d8f8aa548..f4183e4958 100644 --- a/substrate/core/client/src/client.rs +++ b/substrate/core/client/src/client.rs @@ -564,7 +564,7 @@ impl Client where cht_size: NumberFor, ) -> error::Result> { struct AccessedRootsRecorder<'a, Block: BlockT> { - storage: &'a ChangesTrieStorage>, + storage: &'a dyn ChangesTrieStorage>, min: NumberFor, required_roots_proofs: Mutex, H256>>, }; @@ -695,7 +695,7 @@ impl Client where /// Create a new block, built on the head of the chain. pub fn new_block( - &self, + &self, inherent_digests: DigestFor, ) -> error::Result> where E: Clone + Send + Sync, @@ -708,8 +708,8 @@ impl Client where /// Create a new block, built on top of `parent`. pub fn new_block_at( - &self, - parent: &BlockId, + &self, + parent: &BlockId, inherent_digests: DigestFor, ) -> error::Result> where E: Clone + Send + Sync, @@ -726,8 +726,8 @@ impl Client 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, + &self, + parent: &BlockId, inherent_digests: DigestFor, ) -> error::Result> where E: Clone + Send + Sync, @@ -1319,7 +1319,7 @@ impl ProvideCache for Client where B: backend::Backend, Block: BlockT, { - fn cache(&self) -> Option>> { + fn cache(&self) -> Option>> { self.backend.blockchain().cache() } } diff --git a/substrate/core/client/src/error.rs b/substrate/core/client/src/error.rs index bad279f2e4..b807d5e11c 100644 --- a/substrate/core/client/src/error.rs +++ b/substrate/core/client/src/error.rs @@ -42,7 +42,7 @@ pub enum Error { ApplyExtrinsicFailed(ApplyError), /// Execution error. #[display(fmt = "Execution: {}", _0)] - Execution(Box), + Execution(Box), /// Blockchain error. #[display(fmt = "Blockchain: {}", _0)] Blockchain(Box), @@ -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) -> Self { + pub fn from_state(e: Box) -> Self { Error::Execution(e) } } diff --git a/substrate/core/client/src/in_mem.rs b/substrate/core/client/src/in_mem.rs index 6c11d0ed57..92d04230dd 100644 --- a/substrate/core/client/src/in_mem.rs +++ b/substrate/core/client/src/in_mem.rs @@ -343,7 +343,7 @@ impl blockchain::Backend for Blockchain { Ok(self.storage.read().finalized_hash.clone()) } - fn cache(&self) -> Option>> { + fn cache(&self) -> Option>> { None } @@ -357,7 +357,7 @@ impl blockchain::Backend for Blockchain { } impl blockchain::ProvideCache for Blockchain { - fn cache(&self) -> Option>> { + fn cache(&self) -> Option>> { None } } @@ -433,7 +433,7 @@ impl light::blockchain::Storage for Blockchain .ok_or_else(|| error::Error::Backend(format!("Changes trie CHT for block {} not exists", block))) } - fn cache(&self) -> Option>> { + fn cache(&self) -> Option>> { None } } diff --git a/substrate/core/client/src/leaves.rs b/substrate/core/client/src/leaves.rs index 144237f777..b0e49ead80 100644 --- a/substrate/core/client/src/leaves.rs +++ b/substrate/core/client/src/leaves.rs @@ -77,7 +77,7 @@ impl LeafSet where } /// Read the leaf list from the DB, using given prefix for keys. - pub fn read_from_db(db: &KeyValueDB, column: Option, prefix: &[u8]) -> error::Result { + pub fn read_from_db(db: &dyn KeyValueDB, column: Option, prefix: &[u8]) -> error::Result { let mut storage = BTreeMap::new(); for (key, value) in db.iter_from_prefix(column, prefix) { diff --git a/substrate/core/client/src/light/blockchain.rs b/substrate/core/client/src/light/blockchain.rs index 62c13db5a4..e3d9c55a6a 100644 --- a/substrate/core/client/src/light/blockchain.rs +++ b/substrate/core/client/src/light/blockchain.rs @@ -70,7 +70,7 @@ pub trait Storage: AuxStore + BlockchainHeaderBackend { ) -> ClientResult; /// Get storage cache. - fn cache(&self) -> Option>>; + fn cache(&self) -> Option>>; } /// Light client blockchain. @@ -175,7 +175,7 @@ impl BlockchainBackend for Blockchain where Block: Blo self.storage.last_finalized() } - fn cache(&self) -> Option>> { + fn cache(&self) -> Option>> { self.storage.cache() } @@ -189,7 +189,7 @@ impl BlockchainBackend for Blockchain where Block: Blo } impl, F, Block: BlockT> ProvideCache for Blockchain { - fn cache(&self) -> Option>> { + fn cache(&self) -> Option>> { self.storage.cache() } } @@ -303,7 +303,7 @@ pub mod tests { ).into()) } - fn cache(&self) -> Option>> { + fn cache(&self) -> Option>> { None } } diff --git a/substrate/core/client/src/light/call_executor.rs b/substrate/core/client/src/light/call_executor.rs index 5b6d1b3a29..a6b381a8b1 100644 --- a/substrate/core/client/src/light/call_executor.rs +++ b/substrate/core/client/src/light/call_executor.rs @@ -400,7 +400,7 @@ pub fn prove_execution( E: CallExecutor, { let trie_state = state.as_trie_backend() - .ok_or_else(|| Box::new(state_machine::ExecutionError::UnableToGenerateProof) as Box)?; + .ok_or_else(|| Box::new(state_machine::ExecutionError::UnableToGenerateProof) as Box)?; // prepare execution environment + record preparation proof let mut changes = Default::default(); diff --git a/substrate/core/client/src/light/fetcher.rs b/substrate/core/client/src/light/fetcher.rs index f25a2acd30..985aa5bdaa 100644 --- a/substrate/core/client/src/light/fetcher.rs +++ b/substrate/core/client/src/light/fetcher.rs @@ -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).check_read_proof(&RemoteReadRequest::
{ + assert_eq!((&local_checker as &dyn FetchChecker).check_read_proof(&RemoteReadRequest::
{ 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).check_header_proof(&RemoteHeaderRequest::
{ + assert_eq!((&local_checker as &dyn FetchChecker).check_header_proof(&RemoteHeaderRequest::
{ 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).check_header_proof(&RemoteHeaderRequest::
{ + assert!((&local_checker as &dyn FetchChecker).check_header_proof(&RemoteHeaderRequest::
{ 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).check_header_proof(&RemoteHeaderRequest::
{ + assert!((&local_checker as &dyn FetchChecker).check_header_proof(&RemoteHeaderRequest::
{ 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; + let local_checker = &local_checker as &dyn FetchChecker; 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; + let local_checker = &local_checker as &dyn FetchChecker; let max = remote_client.info().chain.best_number; let max_hash = remote_client.info().chain.best_hash; diff --git a/substrate/core/consensus/aura/src/lib.rs b/substrate/core/consensus/aura/src/lib.rs index 263381d5f1..f0d982c36e 100644 --- a/substrate/core/consensus/aura/src/lib.rs +++ b/substrate/core/consensus/aura/src/lib.rs @@ -206,7 +206,7 @@ impl SlotWorker for AuraWorker w DigestItemFor: CompatibleDigestItem

+ DigestItem, Hash=B::Hash>, Error: ::std::error::Error + Send + From<::consensus_common::Error> + From + 'static, { - type OnSlot = Box + Send>; + type OnSlot = Box + Send>; fn on_start( &self, @@ -578,7 +578,7 @@ impl Verifier for AuraVerifier where // skip the inherents verification if the runtime API is old. if self.client .runtime_api() - .has_api_with::, _>(&BlockId::Hash(parent_hash), |v| v >= 2) + .has_api_with::, _>(&BlockId::Hash(parent_hash), |v| v >= 2) .map_err(|e| format!("{:?}", e))? { self.check_inherents( @@ -681,7 +681,7 @@ fn authorities(client: &C, at: &BlockId) -> Result>(at).unwrap_or(false) { + if client.runtime_api().has_api::>(at).unwrap_or(false) { AuthoritiesApi::authorities(&*client.runtime_api(), at).ok() } else { CoreApi::authorities(&*client.runtime_api(), at).ok() diff --git a/substrate/core/consensus/babe/src/lib.rs b/substrate/core/consensus/babe/src/lib.rs index 969c7b8593..12c388d329 100644 --- a/substrate/core/consensus/babe/src/lib.rs +++ b/substrate/core/consensus/babe/src/lib.rs @@ -251,7 +251,7 @@ impl SlotWorker for BabeWorker w SO: SyncOracle + Send + Clone, Error: std::error::Error + Send + From<::consensus_common::Error> + From + 'static, { - type OnSlot = Box + Send>; + type OnSlot = Box + Send>; fn on_start( &self, @@ -715,7 +715,7 @@ fn authorities(client: &C, at: &BlockId) -> 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::>(at).unwrap_or(false) { + if client.runtime_api().has_api::>(at).unwrap_or(false) { AuthoritiesApi::authorities(&*client.runtime_api(), at).ok() } else { panic!("We don’t support deprecated code with new consensus algorithms, \ diff --git a/substrate/core/consensus/common/src/block_import.rs b/substrate/core/consensus/common/src/block_import.rs index 1a6a8d1f50..8ce6019131 100644 --- a/substrate/core/consensus/common/src/block_import.rs +++ b/substrate/core/consensus/common/src/block_import.rs @@ -197,7 +197,7 @@ pub trait JustificationImport { 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) { } + fn on_start(&self, _link: &dyn crate::import_queue::Link) { } /// Import a Block justification and finalize the given block. fn import_justification( @@ -210,10 +210,10 @@ pub trait JustificationImport { /// Finality proof import trait. pub trait FinalityProofImport { - 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) { } + fn on_start(&self, _link: &dyn crate::import_queue::Link) { } /// 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 { hash: B::Hash, number: NumberFor, finality_proof: Vec, - verifier: &Verifier, + verifier: &dyn Verifier, ) -> Result<(B::Hash, NumberFor), Self::Error>; } diff --git a/substrate/core/consensus/common/src/error.rs b/substrate/core/consensus/common/src/error.rs index a923c5f555..d8683d0b68 100644 --- a/substrate/core/consensus/common/src/error.rs +++ b/substrate/core/consensus/common/src/error.rs @@ -64,7 +64,7 @@ pub enum Error { InvalidJustification, /// Some other error. #[display(fmt="Other error: {}", _0)] - Other(Box), + Other(Box), /// Error from the client while importing #[display(fmt="Import failed: {}", _0)] ClientImport(String), diff --git a/substrate/core/consensus/common/src/import_queue.rs b/substrate/core/consensus/common/src/import_queue.rs index d44aa0b93a..118bc641b2 100644 --- a/substrate/core/consensus/common/src/import_queue.rs +++ b/substrate/core/consensus/common/src/import_queue.rs @@ -103,7 +103,7 @@ pub trait ImportQueue: Send + Sync { /// /// This is called automatically by the network service when synchronization /// begins. - fn start(&self, _link: Box>) -> Result<(), std::io::Error> { + fn start(&self, _link: Box>) -> Result<(), std::io::Error> { Ok(()) } /// Import bunch of blocks. @@ -120,7 +120,7 @@ pub struct BasicSyncQueue> { } struct BasicSyncQueueData> { - link: Mutex>>>, + link: Mutex>>>, block_import: SharedBlockImport, verifier: Arc, justification_import: Option>, @@ -147,7 +147,7 @@ impl> BasicSyncQueue { } impl> ImportQueue for BasicSyncQueue { - fn start(&self, link: Box>) -> Result<(), std::io::Error> { + fn start(&self, link: Box>) -> 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 BasicQueue { } impl ImportQueue for BasicQueue { - fn start(&self, link: Box>) -> Result<(), std::io::Error> { + fn start(&self, link: Box>) -> 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 { ImportBlocks(BlockOrigin, Vec>), ImportJustification(Origin, B::Hash, NumberFor, Justification), ImportFinalityProof(Origin, B::Hash, NumberFor, Vec), - Start(Box>, Sender>), + Start(Box>, Sender>), Shutdown(Sender<()>), #[cfg(any(test, feature = "test-helpers"))] Synchronize, @@ -360,7 +360,7 @@ struct BlockImporter { result_port: Receiver>, worker_sender: Option>>, link: Option>>, - verifier: Arc>, + verifier: Arc>, justification_import: Option>, finality_proof_import: Option>, finality_proof_request_builder: Option>, @@ -370,7 +370,7 @@ impl BlockImporter { fn new( result_port: Receiver>, worker_sender: Sender>, - verifier: Arc>, + verifier: Arc>, justification_import: Option>, finality_proof_import: Option>, finality_proof_request_builder: Option>, @@ -667,7 +667,7 @@ pub enum BlockImportError { /// Imports single notification and send notification to the link (if provided). fn import_single_justification( - link: &Option>>, + link: &Option>>, justification_import: &Option>, who: Origin, hash: B::Hash, @@ -723,7 +723,7 @@ fn import_single_finality_proof>( /// Process result of block(s) import. fn process_import_results( - link: &Link, + link: &dyn Link, results: Vec<( Result>, BlockImportError>, B::Hash, @@ -801,7 +801,7 @@ fn process_import_results( /// Import several blocks at once, returning import result for each block. fn import_many_blocks>( - import_handle: &BlockImport, + import_handle: &dyn BlockImport, blocks_origin: BlockOrigin, blocks: Vec>, verifier: Arc, @@ -854,7 +854,7 @@ fn import_many_blocks>( /// Single block import function. pub fn import_single_block>( - import_handle: &BlockImport, + import_handle: &dyn BlockImport, block_origin: BlockOrigin, block: IncomingBlock, verifier: Arc, diff --git a/substrate/core/executor/src/native_executor.rs b/substrate/core/executor/src/native_executor.rs index 729346cbee..c4f3511c9c 100644 --- a/substrate/core/executor/src/native_executor.rs +++ b/substrate/core/executor/src/native_executor.rs @@ -107,7 +107,7 @@ fn safe_call(f: F) -> Result /// 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(ext: &mut Externalities, f: F) -> Result +pub fn with_native_environment(ext: &mut dyn Externalities, f: F) -> Result 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(ext: &mut Externalities, method: &str, data: &[u8]) -> Result>; - fn dispatch(ext: &mut Externalities, method: &str, data: &[u8]) -> Result>; + fn dispatch(ext: &mut dyn Externalities, method: &str, data: &[u8]) -> Result>; /// Provide native runtime version. fn native_version() -> NativeVersion; diff --git a/substrate/core/executor/src/wasm_executor.rs b/substrate/core/executor/src/wasm_executor.rs index 6a3c92b755..920639c0a2 100644 --- a/substrate/core/executor/src/wasm_executor.rs +++ b/substrate/core/executor/src/wasm_executor.rs @@ -1101,7 +1101,7 @@ impl WasmExecutor { /// This should be used for tests only. pub fn call_with_custom_signature< E: Externalities, - F: FnOnce(&mut FnMut(&[u8]) -> Result) -> Result>, + F: FnOnce(&mut dyn FnMut(&[u8]) -> Result) -> Result>, FR: FnOnce(Option, &MemoryRef) -> Result>, 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, - F: FnOnce(&mut FnMut(&[u8]) -> Result) -> Result>, + F: FnOnce(&mut dyn FnMut(&[u8]) -> Result) -> Result>, FR: FnOnce(Option, &MemoryRef) -> Result>, R, >( diff --git a/substrate/core/executor/src/wasm_utils.rs b/substrate/core/executor/src/wasm_utils.rs index a9fbca7f6c..7384f91944 100644 --- a/substrate/core/executor/src/wasm_utils.rs +++ b/substrate/core/executor/src/wasm_utils.rs @@ -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> { diff --git a/substrate/core/finality-grandpa/src/communication/gossip.rs b/substrate/core/finality-grandpa/src/communication/gossip.rs index 79f98e5bdb..460998e707 100644 --- a/substrate/core/finality-grandpa/src/communication/gossip.rs +++ b/substrate/core/finality-grandpa/src/communication/gossip.rs @@ -657,7 +657,7 @@ impl GossipValidator { } impl network_gossip::Validator for GossipValidator { - fn new_peer(&self, context: &mut ValidatorContext, who: &PeerId, _roles: Roles) { + fn new_peer(&self, context: &mut dyn ValidatorContext, who: &PeerId, _roles: Roles) { let packet_data = { let mut inner = self.inner.write(); inner.peers.new_peer(who.clone()); @@ -673,11 +673,11 @@ impl network_gossip::Validator for GossipValidator context.send_message(who, packet_data); } - fn peer_disconnected(&self, _context: &mut ValidatorContext, who: &PeerId) { + fn peer_disconnected(&self, _context: &mut dyn ValidatorContext, who: &PeerId) { self.inner.write().peers.peer_disconnected(who); } - fn validate(&self, context: &mut ValidatorContext, who: &PeerId, data: &[u8]) + fn validate(&self, context: &mut dyn ValidatorContext, who: &PeerId, data: &[u8]) -> network_gossip::ValidationResult { let (action, broadcast_topics) = self.do_validate(who, data); @@ -705,7 +705,7 @@ impl network_gossip::Validator for GossipValidator } fn message_allowed<'a>(&'a self) - -> Box bool + 'a> + -> Box bool + 'a> { let (inner, do_rebroadcast) = { use parking_lot::RwLockWriteGuard; @@ -763,7 +763,7 @@ impl network_gossip::Validator for GossipValidator }) } - fn message_expired<'a>(&'a self) -> Box bool + 'a> { + fn message_expired<'a>(&'a self) -> Box 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, diff --git a/substrate/core/finality-grandpa/src/finality_proof.rs b/substrate/core/finality-grandpa/src/finality_proof.rs index e8af599279..875a60e8e0 100644 --- a/substrate/core/finality-grandpa/src/finality_proof.rs +++ b/substrate/core/finality-grandpa/src/finality_proof.rs @@ -103,7 +103,7 @@ pub trait AuthoritySetForFinalityChecker: Send + Sync { } /// FetchChecker-based implementation of AuthoritySetForFinalityChecker. -impl AuthoritySetForFinalityChecker for Arc> { +impl AuthoritySetForFinalityChecker for Arc> { fn check_authorities_proof( &self, hash: Block::Hash, @@ -132,7 +132,7 @@ impl AuthoritySetForFinalityChecker for Arc, RA> { client: Arc>, - authority_provider: Arc>, + authority_provider: Arc>, } impl, RA> FinalityProofProvider @@ -147,7 +147,7 @@ impl, RA> FinalityProofProvider /// - authority_provider for calling and proving runtime methods. pub fn new( client: Arc>, - authority_provider: Arc>, + authority_provider: Arc>, ) -> Self { FinalityProofProvider { client, authority_provider } } @@ -256,7 +256,7 @@ pub(crate) fn make_finality_proof_request(last_finalized: H, /// Returns None if there are no finalized blocks unknown to the caller. pub(crate) fn prove_finality, B: BlockchainBackend, J>( blockchain: &B, - authorities_provider: &AuthoritySetForFinalityProver, + authorities_provider: &dyn AuthoritySetForFinalityProver, authorities_set_id: u64, begin: Block::Hash, end: Block::Hash, @@ -416,7 +416,7 @@ pub(crate) fn check_finality_proof, B>( blockchain: &B, current_set_id: u64, current_authorities: Vec<(AuthorityId, u64)>, - authorities_provider: &AuthoritySetForFinalityChecker, + authorities_provider: &dyn AuthoritySetForFinalityChecker, remote_proof: Vec, ) -> ClientResult> where @@ -435,7 +435,7 @@ fn do_check_finality_proof, B, J>( blockchain: &B, current_set_id: u64, current_authorities: Vec<(AuthorityId, u64)>, - authorities_provider: &AuthoritySetForFinalityChecker, + authorities_provider: &dyn AuthoritySetForFinalityChecker, remote_proof: Vec, ) -> ClientResult> where @@ -489,7 +489,7 @@ fn do_check_finality_proof, B, J>( fn check_finality_proof_fragment, B, J>( blockchain: &B, authority_set: AuthoritiesOrEffects, - authorities_provider: &AuthoritySetForFinalityChecker, + authorities_provider: &dyn AuthoritySetForFinalityChecker, proof_fragment: FinalityProofFragment, ) -> ClientResult> where diff --git a/substrate/core/finality-grandpa/src/import.rs b/substrate/core/finality-grandpa/src/import.rs index d68793c047..ed57c68250 100644 --- a/substrate/core/finality-grandpa/src/import.rs +++ b/substrate/core/finality-grandpa/src/import.rs @@ -76,7 +76,7 @@ impl, RA, PRA, SC> JustificationImport { type Error = ConsensusError; - fn on_start(&self, link: &::consensus_common::import_queue::Link) { + fn on_start(&self, link: &dyn consensus_common::import_queue::Link) { 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::, _>(&at, |v| v >= 2) { + Err(e) => match api.has_api_with::, _>(&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 diff --git a/substrate/core/finality-grandpa/src/light_import.rs b/substrate/core/finality-grandpa/src/light_import.rs index 73bc3411fe..c70f91d0f3 100644 --- a/substrate/core/finality-grandpa/src/light_import.rs +++ b/substrate/core/finality-grandpa/src/light_import.rs @@ -53,7 +53,7 @@ const LIGHT_CONSENSUS_CHANGES_KEY: &[u8] = b"grandpa_consensus_changes"; /// Create light block importer. pub fn light_block_import, RA, PRA>( client: Arc>, - authority_set_provider: Arc>, + authority_set_provider: Arc>, api: Arc, ) -> Result, ClientError> where @@ -80,7 +80,7 @@ pub fn light_block_import, RA, PRA>( /// - fetching finality proofs for blocks that are enacting consensus changes. pub struct GrandpaLightBlockImport, RA> { client: Arc>, - authority_set_provider: Arc>, + authority_set_provider: Arc>, data: Arc>>, } @@ -144,7 +144,7 @@ impl, RA> FinalityProofImport { type Error = ConsensusError; - fn on_start(&self, link: &::consensus_common::import_queue::Link) { + fn on_start(&self, link: &dyn consensus_common::import_queue::Link) { let chain_info = self.client.info().chain; let data = self.data.read(); @@ -160,7 +160,7 @@ impl, RA> FinalityProofImport hash: Block::Hash, number: NumberFor, finality_proof: Vec, - verifier: &Verifier, + verifier: &dyn Verifier, ) -> Result<(Block::Hash, NumberFor), Self::Error> { do_import_finality_proof::<_, _, _, _, GrandpaJustification>( &*self.client, @@ -271,12 +271,12 @@ fn do_import_block, RA, J>( /// Try to import finality proof. fn do_import_finality_proof, RA, J>( client: &Client, - authority_set_provider: &AuthoritySetForFinalityChecker, + authority_set_provider: &dyn AuthoritySetForFinalityChecker, data: &mut LightImportData, _hash: Block::Hash, _number: NumberFor, finality_proof: Vec, - verifier: &Verifier, + verifier: &dyn Verifier, ) -> Result<(Block::Hash, NumberFor), ConsensusError> where B: Backend + 'static, @@ -572,7 +572,7 @@ pub mod tests { { type Error = ConsensusError; - fn on_start(&self, link: &::consensus_common::import_queue::Link) { + fn on_start(&self, link: &dyn consensus_common::import_queue::Link) { self.0.on_start(link) } @@ -581,7 +581,7 @@ pub mod tests { hash: Block::Hash, number: NumberFor, finality_proof: Vec, - verifier: &Verifier, + verifier: &dyn Verifier, ) -> Result<(Block::Hash, NumberFor), 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, RA, PRA>( client: Arc>, - authority_set_provider: Arc>, + authority_set_provider: Arc>, api: Arc, ) -> Result, ClientError> where diff --git a/substrate/core/finality-grandpa/src/tests.rs b/substrate/core/finality-grandpa/src/tests.rs index ef04396b5f..51028fad84 100644 --- a/substrate/core/finality-grandpa/src/tests.rs +++ b/substrate/core/finality-grandpa/src/tests.rs @@ -150,7 +150,10 @@ impl TestNetFactory for GrandpaTestNet { } } - fn make_finality_proof_provider(&self, client: PeersClient) -> Option>> { + fn make_finality_proof_provider( + &self, + client: PeersClient + ) -> Option>> { match client { PeersClient::Full(ref client) => { let authorities_provider = Arc::new(self.test_config.clone()); @@ -201,7 +204,7 @@ impl MessageRouting { } impl Network for MessageRouting { - type In = Box + Send>; + type In = Box + 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( peers: &[AuthorityKeyring], with: F, ) -> u64 where - F: FnOnce(current_thread::Handle) -> Option>> + F: FnOnce(current_thread::Handle) -> Option>> { use parking_lot::RwLock; diff --git a/substrate/core/keyring/src/sr25519.rs b/substrate/core/keyring/src/sr25519.rs index 0097d7b2f9..24a83ab798 100644 --- a/substrate/core/keyring/src/sr25519.rs +++ b/substrate/core/keyring/src/sr25519.rs @@ -68,7 +68,7 @@ impl Keyring { } pub fn to_raw_public_vec(self) -> Vec { - Public::from(self).to_raw_vec() + Public::from(self).into_raw_vec() } pub fn sign(self, msg: &[u8]) -> Signature { diff --git a/substrate/core/network/src/config.rs b/substrate/core/network/src/config.rs index e6c1a4ddd5..d8fd0f68c7 100644 --- a/substrate/core/network/src/config.rs +++ b/substrate/core/network/src/config.rs @@ -35,9 +35,9 @@ pub struct Params { /// Network layer configuration. pub network_config: NetworkConfiguration, /// Substrate relay chain access point. - pub chain: Arc>, + pub chain: Arc>, /// Finality proof provider. - pub finality_proof_provider: Option>>, + pub finality_proof_provider: Option>>, /// On-demand service reference. pub on_demand: Option>>, /// Transaction pool. @@ -45,7 +45,7 @@ pub struct Params { /// 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>, + pub import_queue: Box>, /// Protocol specialization. pub specialization: S, } diff --git a/substrate/core/network/src/consensus_gossip.rs b/substrate/core/network/src/consensus_gossip.rs index c5f1a2d927..9d654b5bfa 100644 --- a/substrate/core/network/src/consensus_gossip.rs +++ b/substrate/core/network/src/consensus_gossip.rs @@ -110,7 +110,7 @@ pub trait ValidatorContext { struct NetworkContext<'g, 'p, B: BlockT> { gossip: &'g mut ConsensusGossip, - protocol: &'p mut Context, + protocol: &'p mut dyn Context, engine_id: ConsensusEngineId, } @@ -145,11 +145,11 @@ impl<'g, 'p, B: BlockT> ValidatorContext for NetworkContext<'g, 'p, B> { } fn propagate<'a, B: BlockT, I>( - protocol: &mut Context, + protocol: &mut dyn Context, messages: I, intent: MessageIntent, peers: &mut HashMap>, - validators: &HashMap>>, + validators: &HashMap>>, ) where I: IntoIterator, // (msg_hash, topic, message) { @@ -200,23 +200,23 @@ fn propagate<'a, B: BlockT, I>( /// Validates consensus messages. pub trait Validator: Send + Sync { /// New peer is connected. - fn new_peer(&self, _context: &mut ValidatorContext, _who: &PeerId, _roles: Roles) { + fn new_peer(&self, _context: &mut dyn ValidatorContext, _who: &PeerId, _roles: Roles) { } /// New connection is dropped. - fn peer_disconnected(&self, _context: &mut ValidatorContext, _who: &PeerId) { + fn peer_disconnected(&self, _context: &mut dyn ValidatorContext, _who: &PeerId) { } /// Validate consensus message. - fn validate(&self, context: &mut ValidatorContext, sender: &PeerId, data: &[u8]) -> ValidationResult; + fn validate(&self, context: &mut dyn ValidatorContext, sender: &PeerId, data: &[u8]) -> ValidationResult; /// Produce a closure for validating messages on a given topic. - fn message_expired<'a>(&'a self) -> Box bool + 'a> { + fn message_expired<'a>(&'a self) -> Box bool + 'a> { Box::new(move |_topic, _data| false) } /// Produce a closure for filtering egress messages. - fn message_allowed<'a>(&'a self) -> Box bool + 'a> { + fn message_allowed<'a>(&'a self) -> Box bool + 'a> { Box::new(move |_who, _intent, _topic, _data| true) } } @@ -227,7 +227,7 @@ pub struct ConsensusGossip { live_message_sinks: HashMap<(ConsensusEngineId, B::Hash), Vec>>, messages: Vec>, known_messages: LruCache, - validators: HashMap>>, + validators: HashMap>>, next_broadcast: time::Instant, } @@ -250,7 +250,12 @@ impl ConsensusGossip { } /// Register message validator for a message type. - pub fn register_validator(&mut self, protocol: &mut Context, engine_id: ConsensusEngineId, validator: Arc>) { + pub fn register_validator( + &mut self, + protocol: &mut dyn Context, + engine_id: ConsensusEngineId, + validator: Arc> + ) { 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 ConsensusGossip { } } - fn register_validator_internal(&mut self, engine_id: ConsensusEngineId, validator: Arc>) { + fn register_validator_internal(&mut self, engine_id: ConsensusEngineId, validator: Arc>) { self.validators.insert(engine_id, validator.clone()); } /// Handle new connected peer. - pub fn new_peer(&mut self, protocol: &mut Context, who: PeerId, roles: Roles) { + pub fn new_peer(&mut self, protocol: &mut dyn Context, who: PeerId, roles: Roles) { // light nodes are not valid targets for consensus gossip messages if !roles.is_full() { return; @@ -311,7 +316,7 @@ impl ConsensusGossip { } /// Call when a peer has been disconnected to stop tracking gossip status. - pub fn peer_disconnected(&mut self, protocol: &mut Context, who: PeerId) { + pub fn peer_disconnected(&mut self, protocol: &mut dyn Context, 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 ConsensusGossip { } /// Perform periodic maintenance - pub fn tick(&mut self, protocol: &mut Context) { + pub fn tick(&mut self, protocol: &mut dyn Context) { self.collect_garbage(); if time::Instant::now() >= self.next_broadcast { self.rebroadcast(protocol); @@ -328,14 +333,14 @@ impl ConsensusGossip { } /// Rebroadcast all messages to all peers. - fn rebroadcast(&mut self, protocol: &mut Context) { + fn rebroadcast(&mut self, protocol: &mut dyn Context) { 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, topic: B::Hash, force: bool) { + pub fn broadcast_topic(&mut self, protocol: &mut dyn Context, 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 ConsensusGossip { /// in all other cases. pub fn on_incoming( &mut self, - protocol: &mut Context, + protocol: &mut dyn Context, who: PeerId, message: ConsensusMessage, ) { @@ -473,7 +478,14 @@ impl ConsensusGossip { } /// Send all messages with given topic to a peer. - pub fn send_topic(&mut self, protocol: &mut Context, who: &PeerId, topic: B::Hash, engine_id: ConsensusEngineId, force: bool) { + pub fn send_topic( + &mut self, + protocol: &mut dyn Context, + 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 ConsensusGossip { /// Multicast a message to all peers. pub fn multicast( &mut self, - protocol: &mut Context, + protocol: &mut dyn Context, topic: B::Hash, message: ConsensusMessage, force: bool, @@ -518,7 +530,7 @@ impl ConsensusGossip { /// later on. pub fn send_message( &mut self, - protocol: &mut Context, + protocol: &mut dyn Context, who: &PeerId, message: ConsensusMessage, ) { @@ -559,7 +571,12 @@ mod tests { struct AllowAll; impl Validator for AllowAll { - fn validate(&self, _context: &mut ValidatorContext, _sender: &PeerId, _data: &[u8]) -> ValidationResult { + fn validate( + &self, + _context: &mut dyn ValidatorContext, + _sender: &PeerId, + _data: &[u8], + ) -> ValidationResult { ValidationResult::ProcessAndKeep(H256::default()) } } @@ -568,7 +585,12 @@ mod tests { fn collects_garbage() { struct AllowOne; impl Validator for AllowOne { - fn validate(&self, _context: &mut ValidatorContext, _sender: &PeerId, data: &[u8]) -> ValidationResult { + fn validate( + &self, + _context: &mut dyn ValidatorContext, + _sender: &PeerId, + data: &[u8], + ) -> ValidationResult { if data[0] == 1 { ValidationResult::ProcessAndKeep(H256::default()) } else { @@ -576,7 +598,7 @@ mod tests { } } - fn message_expired<'a>(&'a self) -> Box bool + 'a> { + fn message_expired<'a>(&'a self) -> Box bool + 'a> { Box::new(move |_topic, data| data[0] != 1 ) } } diff --git a/substrate/core/network/src/on_demand_layer.rs b/substrate/core/network/src/on_demand_layer.rs index 95f9f4d67b..e58e045f2e 100644 --- a/substrate/core/network/src/on_demand_layer.rs +++ b/substrate/core/network/src/on_demand_layer.rs @@ -50,7 +50,7 @@ impl OnDemand where B::Header: HeaderT, { /// Creates new on-demand service. - pub fn new(checker: Arc>) -> Self { + pub fn new(checker: Arc>) -> Self { let (requests_send, requests_queue) = mpsc::unbounded(); let requests_queue = Mutex::new(Some(requests_queue)); @@ -62,7 +62,7 @@ impl OnDemand where } /// Get checker reference. - pub fn checker(&self) -> &Arc> { + pub fn checker(&self) -> &Arc> { &self.checker } diff --git a/substrate/core/network/src/protocol.rs b/substrate/core/network/src/protocol.rs index b660e097a1..569f1df030 100644 --- a/substrate/core/network/src/protocol.rs +++ b/substrate/core/network/src/protocol.rs @@ -346,7 +346,7 @@ impl<'a, B: BlockT + 'a, H: ExHashT + 'a> SyncContext for ProtocolContext<'a, self.context_data.peers.get(who).map(|p| p.info.clone()) } - fn client(&self) -> &Client { + fn client(&self) -> &dyn Client { &*self.context_data.chain } @@ -373,7 +373,7 @@ impl<'a, B: BlockT + 'a, H: ExHashT + 'a> SyncContext for ProtocolContext<'a, struct ContextData { // All connected peers peers: HashMap>, - pub chain: Arc>, + pub chain: Arc>, } /// Configuration for the Substrate-specific part of the networking layer. @@ -395,7 +395,7 @@ impl, H: ExHashT> Protocol { /// Create a new instance. pub fn new( config: ProtocolConfig, - chain: Arc>, + chain: Arc>, checker: Arc>, specialization: S, ) -> error::Result> { @@ -510,7 +510,7 @@ impl, H: ExHashT> Protocol { transaction_pool: &(impl TransactionPool + ?Sized), who: PeerId, message: Message, - finality_proof_provider: Option<&FinalityProofProvider> + finality_proof_provider: Option<&dyn FinalityProofProvider> ) -> CustomMessageOutcome { match message { GenericMessage::Status(s) => self.on_status_message(network_out, who, s), @@ -1399,7 +1399,7 @@ impl, H: ExHashT> Protocol { network_out: &mut dyn NetworkOut, who: PeerId, request: message::FinalityProofRequest, - finality_proof_provider: Option<&FinalityProofProvider> + finality_proof_provider: Option<&dyn FinalityProofProvider> ) { trace!(target: "sync", "Finality proof request from {} for {}", who, request.block); let finality_proof = finality_proof_provider.as_ref() diff --git a/substrate/core/network/src/service.rs b/substrate/core/network/src/service.rs index c7a32d472f..88c13b4806 100644 --- a/substrate/core/network/src/service.rs +++ b/substrate/core/network/src/service.rs @@ -358,7 +358,7 @@ impl> NetworkService { /// Execute a closure with the chain-specific network specialization. pub fn with_spec(&self, f: F) - where F: FnOnce(&mut S, &mut Context) + Send + 'static + where F: FnOnce(&mut S, &mut dyn Context) + Send + 'static { let _ = self .protocol_sender @@ -367,7 +367,7 @@ impl> NetworkService { /// Execute a closure with the consensus gossip. pub fn with_gossip(&self, f: F) - where F: FnOnce(&mut ConsensusGossip, &mut Context) + Send + 'static + where F: FnOnce(&mut ConsensusGossip, &mut dyn Context) + Send + 'static { let _ = self .protocol_sender @@ -489,9 +489,9 @@ pub enum ProtocolMsg> { /// 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 + Send + 'static>), + ExecuteWithSpec(Box + Send + 'static>), /// Execute a closure with the consensus gossip. - ExecuteWithGossip(Box + Send + 'static>), + ExecuteWithGossip(Box + Send + 'static>), /// Incoming gossip consensus message. GossipConsensusMessage(B::Hash, ConsensusEngineId, Vec, GossipMessageRecipient), /// Tell protocol to perform regular maintenance. @@ -504,22 +504,22 @@ pub enum ProtocolMsg> { /// A task, consisting of a user-provided closure, to be executed on the Protocol thread. pub trait SpecTask> { - fn call_box(self: Box, spec: &mut S, context: &mut Context); + fn call_box(self: Box, spec: &mut S, context: &mut dyn Context); } -impl, F: FnOnce(&mut S, &mut Context)> SpecTask for F { - fn call_box(self: Box, spec: &mut S, context: &mut Context) { +impl, F: FnOnce(&mut S, &mut dyn Context)> SpecTask for F { + fn call_box(self: Box, spec: &mut S, context: &mut dyn Context) { (*self)(spec, context) } } /// A task, consisting of a user-provided closure, to be executed on the Protocol thread. pub trait GossipTask { - fn call_box(self: Box, gossip: &mut ConsensusGossip, context: &mut Context); + fn call_box(self: Box, gossip: &mut ConsensusGossip, context: &mut dyn Context); } -impl, &mut Context)> GossipTask for F { - fn call_box(self: Box, gossip: &mut ConsensusGossip, context: &mut Context) { +impl, &mut dyn Context)> GossipTask for F { + fn call_box(self: Box, gossip: &mut ConsensusGossip, context: &mut dyn Context) { (*self)(gossip, context) } } @@ -535,9 +535,9 @@ pub struct NetworkWorker, H: Ex service: Arc>, network_service: Arc>>>, peers: Arc>>>, - import_queue: Box>, + import_queue: Box>, transaction_pool: Arc>, - finality_proof_provider: Option>>, + finality_proof_provider: Option>>, network_port: mpsc::UnboundedReceiver>, protocol_rx: mpsc::UnboundedReceiver>, status_sinks: Arc>>>>, diff --git a/substrate/core/network/src/specialization.rs b/substrate/core/network/src/specialization.rs index 2778146b52..772a1bcbe1 100644 --- a/substrate/core/network/src/specialization.rs +++ b/substrate/core/network/src/specialization.rs @@ -25,15 +25,15 @@ pub trait NetworkSpecialization: Send + Sync + 'static { fn status(&self) -> Vec; /// Called when a peer successfully handshakes. - fn on_connect(&mut self, ctx: &mut Context, who: PeerId, status: crate::message::Status); + fn on_connect(&mut self, ctx: &mut dyn Context, who: PeerId, status: crate::message::Status); /// Called when a peer is disconnected. If the peer ID is unknown, it should be ignored. - fn on_disconnect(&mut self, ctx: &mut Context, who: PeerId); + fn on_disconnect(&mut self, ctx: &mut dyn Context, who: PeerId); /// Called when a network-specific message arrives. fn on_message( &mut self, - ctx: &mut Context, + ctx: &mut dyn Context, who: PeerId, message: &mut Option> ); @@ -43,11 +43,11 @@ pub trait NetworkSpecialization: Send + Sync + 'static { fn on_abort(&mut self) { } /// Called periodically to maintain peers and handle timeouts. - fn maintain_peers(&mut self, _ctx: &mut Context) { } + fn maintain_peers(&mut self, _ctx: &mut dyn Context) { } /// 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, _hash: B::Hash, _header: &B::Header) { } + fn on_block_imported(&mut self, _ctx: &mut dyn Context, _hash: B::Hash, _header: &B::Header) { } } /// Context for a network-specific handler. diff --git a/substrate/core/network/src/sync.rs b/substrate/core/network/src/sync.rs index 27a412ca0e..9b327c1a20 100644 --- a/substrate/core/network/src/sync.rs +++ b/substrate/core/network/src/sync.rs @@ -72,7 +72,7 @@ const GENESIS_MISMATCH_REPUTATION_CHANGE: i32 = i32::min_value() + 1; /// Context for a network-specific handler. pub trait Context { /// Get a reference to the client. - fn client(&self) -> &crate::chain::Client; + fn client(&self) -> &dyn crate::chain::Client; /// 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 { /// Relay chain sync strategy. pub struct ChainSync { - genesis_hash: B::Hash, + _genesis_hash: B::Hash, peers: HashMap>, blocks: BlockCollection, best_queued_number: NumberFor, @@ -191,7 +191,7 @@ impl ChainSync { } 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 ChainSync { 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, who: PeerId) { + pub(crate) fn new_peer(&mut self, protocol: &mut dyn Context, 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 ChainSync { #[must_use] pub(crate) fn on_block_data( &mut self, - protocol: &mut Context, + protocol: &mut dyn Context, who: PeerId, request: message::BlockRequest, response: message::BlockResponse @@ -483,7 +483,7 @@ impl ChainSync { #[must_use] pub(crate) fn on_block_justification_data( &mut self, - protocol: &mut Context, + protocol: &mut dyn Context, who: PeerId, _request: message::BlockRequest, response: message::BlockResponse, @@ -528,7 +528,7 @@ impl ChainSync { /// Handle new finality proof data. pub(crate) fn on_block_finality_proof_data( &mut self, - protocol: &mut Context, + protocol: &mut dyn Context, who: PeerId, response: message::FinalityProofResponse, ) -> Option<(PeerId, B::Hash, NumberFor, Vec)> { @@ -573,7 +573,7 @@ impl ChainSync { } /// Maintain the sync process (download new blocks, fetch justifications). - pub fn maintain_sync(&mut self, protocol: &mut Context) { + pub fn maintain_sync(&mut self, protocol: &mut dyn Context) { let peers: Vec = self.peers.keys().map(|p| p.clone()).collect(); for peer in peers { self.download_new(protocol, peer); @@ -583,7 +583,7 @@ impl ChainSync { /// Called periodically to perform any time-based actions. Must be called at a regular /// interval. - pub fn tick(&mut self, protocol: &mut Context) { + pub fn tick(&mut self, protocol: &mut dyn Context) { self.extra_requests.dispatch(&mut self.peers, protocol); } @@ -591,7 +591,7 @@ impl ChainSync { /// /// 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, protocol: &mut Context) { + pub fn request_justification(&mut self, hash: &B::Hash, number: NumberFor, protocol: &mut dyn Context) { self.extra_requests.justifications().queue_request( (*hash, number), |base, block| protocol.client().is_descendent_of(base, block), @@ -620,7 +620,7 @@ impl ChainSync { /// 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, protocol: &mut Context) { + pub fn request_finality_proof(&mut self, hash: &B::Hash, number: NumberFor, protocol: &mut dyn Context) { self.extra_requests.finality_proofs().queue_request( (*hash, number), |base, block| protocol.client().is_descendent_of(base, block), @@ -647,7 +647,7 @@ impl ChainSync { } /// Notify about finalization of the given block. - pub fn on_block_finalized(&mut self, hash: &B::Hash, number: NumberFor, protocol: &mut Context) { + pub fn on_block_finalized(&mut self, hash: &B::Hash, number: NumberFor, protocol: &mut dyn Context) { if let Err(err) = self.extra_requests.on_block_finalized( hash, number, @@ -699,7 +699,7 @@ impl ChainSync { #[must_use] pub(crate) fn on_block_announce( &mut self, - protocol: &mut Context, + protocol: &mut dyn Context, who: PeerId, hash: B::Hash, header: &B::Header, @@ -812,12 +812,12 @@ impl ChainSync { self.peers.iter().any(|(_, p)| p.state == PeerSyncState::DownloadingStale(*hash)) } - fn is_known(&self, protocol: &mut Context, hash: &B::Hash) -> bool { + fn is_known(&self, protocol: &mut dyn Context, 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, who: PeerId) { + pub(crate) fn peer_disconnected(&mut self, protocol: &mut dyn Context, who: PeerId) { self.blocks.clear_peer_download(&who); self.peers.remove(&who); self.extra_requests.peer_disconnected(who); @@ -825,7 +825,7 @@ impl ChainSync { } /// Restart the sync process. - pub(crate) fn restart(&mut self, protocol: &mut Context) { + pub(crate) fn restart(&mut self, protocol: &mut dyn Context) { self.queue_blocks.clear(); self.best_importing_number = Zero::zero(); self.blocks.clear(); @@ -886,7 +886,7 @@ impl ChainSync { } // Issue a request for a peer to download new blocks, if any are available. - fn download_new(&mut self, protocol: &mut Context, who: PeerId) { + fn download_new(&mut self, protocol: &mut dyn Context, who: PeerId) { if let Some((_, request)) = self.select_new_blocks(who.clone()) { protocol.send_block_request(who, request); } @@ -942,7 +942,7 @@ impl ChainSync { } } - fn request_ancestry(protocol: &mut Context, who: PeerId, block: NumberFor) { + fn request_ancestry(protocol: &mut dyn Context, who: PeerId, block: NumberFor) { trace!(target: "sync", "Requesting ancestry block #{} from {}", block, who); let request = message::generic::BlockRequest { id: 0, @@ -958,7 +958,7 @@ impl ChainSync { /// Get block status, taking into account import queue. fn block_status( - chain: &crate::chain::Client, + chain: &dyn crate::chain::Client, queue_blocks: &HashSet, hash: B::Hash) -> Result { diff --git a/substrate/core/network/src/sync/extra_requests.rs b/substrate/core/network/src/sync/extra_requests.rs index 3ebf2b2509..ff8323166b 100644 --- a/substrate/core/network/src/sync/extra_requests.rs +++ b/substrate/core/network/src/sync/extra_requests.rs @@ -39,7 +39,7 @@ pub(crate) trait ExtraRequestsEssence { /// 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, peer: PeerId, request: ExtraRequest); + fn send_network_request(&self, protocol: &mut dyn Context, peer: PeerId, request: ExtraRequest); /// Create peer state for peer that is downloading extra data. fn peer_downloading_state(&self, block: B::Hash) -> PeerSyncState; } @@ -69,7 +69,7 @@ impl ExtraRequestsAggregator { } /// Dispatches all possible pending requests to the given peers. - pub(crate) fn dispatch(&mut self, peers: &mut HashMap>, protocol: &mut Context) { + pub(crate) fn dispatch(&mut self, peers: &mut HashMap>, protocol: &mut dyn Context) { self.justifications.dispatch(peers, protocol); self.finality_proofs.dispatch(peers, protocol); } @@ -132,7 +132,7 @@ impl> ExtraRequests { /// 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>, protocol: &mut Context) { + pub(crate) fn dispatch(&mut self, peers: &mut HashMap>, protocol: &mut dyn Context) { if self.pending_requests.is_empty() { return; } @@ -373,7 +373,7 @@ impl ExtraRequestsEssence for JustificationsRequestsEssence { "justification" } - fn send_network_request(&self, protocol: &mut Context, peer: PeerId, request: ExtraRequest) { + fn send_network_request(&self, protocol: &mut dyn Context, peer: PeerId, request: ExtraRequest) { protocol.send_block_request(peer, message::generic::BlockRequest { id: 0, fields: message::BlockAttributes::JUSTIFICATION, @@ -398,7 +398,7 @@ impl ExtraRequestsEssence for FinalityProofRequestsEssence { "finality proof" } - fn send_network_request(&self, protocol: &mut Context, peer: PeerId, request: ExtraRequest) { + fn send_network_request(&self, protocol: &mut dyn Context, peer: PeerId, request: ExtraRequest) { protocol.send_finality_proof_request(peer, message::generic::FinalityProofRequest { id: 0, block: request.0, diff --git a/substrate/core/network/src/test/mod.rs b/substrate/core/network/src/test/mod.rs index b47cef11ac..b9703d71e0 100644 --- a/substrate/core/network/src/test/mod.rs +++ b/substrate/core/network/src/test/mod.rs @@ -103,22 +103,19 @@ impl NetworkSpecialization for DummySpecialization { fn on_connect( &mut self, - _ctx: &mut SpecializationContext, + _ctx: &mut dyn SpecializationContext, _peer_id: PeerId, _status: crate::message::Status - ) { - } + ) {} - fn on_disconnect(&mut self, _ctx: &mut SpecializationContext, _peer_id: PeerId) { - } + fn on_disconnect(&mut self, _ctx: &mut dyn SpecializationContext, _peer_id: PeerId) {} fn on_message( &mut self, - _ctx: &mut SpecializationContext, + _ctx: &mut dyn SpecializationContext, _peer_id: PeerId, _message: &mut Option>, - ) { - } + ) {} } pub type PeersFullClient = @@ -292,7 +289,7 @@ pub struct Peer> { finalized_hash: Mutex>, } -type MessageFilter = Fn(&NetworkMsg) -> bool; +type MessageFilter = dyn Fn(&NetworkMsg) -> bool; pub enum FromNetworkMsg { /// A peer connected, with debug info. @@ -605,7 +602,7 @@ impl> Peer { /// Execute a closure with the consensus gossip. pub fn with_gossip(&self, f: F) - where F: FnOnce(&mut ConsensusGossip, &mut Context) + Send + 'static + where F: FnOnce(&mut ConsensusGossip, &mut dyn Context) + 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>> { + fn make_finality_proof_provider(&self, _client: PeersClient) -> Option>> { None } @@ -799,7 +796,7 @@ pub trait TestNetFactory: Sized { protocol_status: Arc>>, import_queue: Box>, tx_pool: EmptyTransactionPool, - finality_proof_provider: Option>>, + finality_proof_provider: Option>>, mut protocol: Protocol, network_sender: mpsc::UnboundedSender>, mut network_to_protocol_rx: mpsc::UnboundedReceiver>, diff --git a/substrate/core/offchain/src/lib.rs b/substrate/core/offchain/src/lib.rs index 376f41b445..081ae61a5b 100644 --- a/substrate/core/offchain/src/lib.rs +++ b/substrate/core/offchain/src/lib.rs @@ -91,7 +91,7 @@ impl OffchainWorkers where { let runtime = self.client.runtime_api(); let at = BlockId::number(*number); - let has_api = runtime.has_api::>(&at); + let has_api = runtime.has_api::>(&at); debug!("Checking offchain workers at {:?}: {:?}", at, has_api); if has_api.unwrap_or(false) { diff --git a/substrate/core/primitives/src/hexdisplay.rs b/substrate/core/primitives/src/hexdisplay.rs index d748208d0e..cd2b6c18cb 100644 --- a/substrate/core/primitives/src/hexdisplay.rs +++ b/substrate/core/primitives/src/hexdisplay.rs @@ -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('#'); diff --git a/substrate/core/primitives/src/lib.rs b/substrate/core/primitives/src/lib.rs index 69b9f1a960..7c0fd324fe 100644 --- a/substrate/core/primitives/src/lib.rs +++ b/substrate/core/primitives/src/lib.rs @@ -86,7 +86,7 @@ pub enum ExecutionContext { /// Context used for block construction. BlockConstruction, /// Offchain worker context. - OffchainWorker(Box), + OffchainWorker(Box), /// Context used for other calls. Other, } diff --git a/substrate/core/primitives/src/offchain.rs b/substrate/core/primitives/src/offchain.rs index 764837d7b4..7d54c9d61e 100644 --- a/substrate/core/primitives/src/offchain.rs +++ b/substrate/core/primitives/src/offchain.rs @@ -35,8 +35,8 @@ impl TryFrom for CryptoKind { fn try_from(kind: u32) -> Result { 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 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 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(()), } } diff --git a/substrate/core/primitives/src/sr25519.rs b/substrate/core/primitives/src/sr25519.rs index 8f309ec030..876dcb7078 100644 --- a/substrate/core/primitives/src/sr25519.rs +++ b/substrate/core/primitives/src/sr25519.rs @@ -204,16 +204,16 @@ impl From 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(&self, state: &mut H) { - ::std::hash::Hash::hash(&self.0[..], state); +impl std::hash::Hash for Signature { + fn hash(&self, state: &mut H) { + std::hash::Hash::hash(&self.0[..], state); } } @@ -304,15 +304,13 @@ impl Public { /// Return a `Vec` filled with raw data. #[cfg(feature = "std")] - pub fn to_raw_vec(self) -> Vec { - let r: &[u8; 32] = self.as_ref(); - r.to_vec() + pub fn into_raw_vec(self) -> Vec { + 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(); diff --git a/substrate/core/rpc/src/author/error.rs b/substrate/core/rpc/src/author/error.rs index 5955108249..008a70b674 100644 --- a/substrate/core/rpc/src/author/error.rs +++ b/substrate/core/rpc/src/author/error.rs @@ -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), /// Incorrect extrinsic format. #[display(fmt="Invalid extrinsic format")] BadFormat, diff --git a/substrate/core/rpc/src/system/mod.rs b/substrate/core/rpc/src/system/mod.rs index 8aac02b77d..d6f2b75515 100644 --- a/substrate/core/rpc/src/system/mod.rs +++ b/substrate/core/rpc/src/system/mod.rs @@ -74,7 +74,7 @@ pub trait SystemApi { /// System API implementation pub struct System { info: SystemInfo, - sync: Arc>, + sync: Arc>, should_have_peers: bool, } @@ -82,7 +82,7 @@ impl System { /// Creates new `System` given the `SystemInfo`. pub fn new( info: SystemInfo, - sync: Arc>, + sync: Arc>, should_have_peers: bool, ) -> Self { System { diff --git a/substrate/core/service/src/chain_ops.rs b/substrate/core/service/src/chain_ops.rs index 3be3b9b17a..83f103ec8f 100644 --- a/substrate/core/service/src/chain_ops.rs +++ b/substrate/core/service/src/chain_ops.rs @@ -151,7 +151,7 @@ pub fn import_blocks( let (header, extrinsics) = signed.block.deconstruct(); let hash = header.hash(); let block = message::BlockData:: { - hash: hash, + hash, justification: signed.justification, header: Some(header), body: Some(extrinsics), diff --git a/substrate/core/service/src/components.rs b/substrate/core/service/src/components.rs index 3876279cc7..a314588d0a 100644 --- a/substrate/core/service/src/components.rs +++ b/substrate/core/service/src/components.rs @@ -139,7 +139,7 @@ pub trait StartRPC { fn start_rpc( client: Arc>, - network: Arc>>, + network: Arc>>, should_have_peers: bool, system_info: SystemInfo, rpc_http: Option, @@ -159,7 +159,7 @@ impl StartRPC for C where fn start_rpc( client: Arc>, - network: Arc>>, + network: Arc>>, should_have_peers: bool, rpc_system_info: SystemInfo, rpc_http: Option, @@ -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> - ) -> Result>>, error::Error>; + ) -> Result>>, 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> - ) -> Result::Block>>>, error::Error>; + ) -> Result::Block>>>, error::Error>; /// Build fork choice selector fn build_select_chain( @@ -536,7 +536,7 @@ impl Components for FullComponents { fn build_finality_proof_provider( client: Arc> - ) -> Result::Block>>>, error::Error> { + ) -> Result::Block>>>, error::Error> { Factory::build_finality_proof_provider(client) } } @@ -619,7 +619,7 @@ impl Components for LightComponents { fn build_finality_proof_provider( _client: Arc> - ) -> Result::Block>>>, error::Error> { + ) -> Result::Block>>>, error::Error> { Ok(None) } fn build_select_chain( diff --git a/substrate/core/service/src/lib.rs b/substrate/core/service/src/lib.rs index 0e16d2e7be..bc40d6008b 100644 --- a/substrate/core/service/src/lib.rs +++ b/substrate/core/service/src/lib.rs @@ -80,7 +80,7 @@ pub struct Service { signal: Option, /// Configuration of this Service pub config: FactoryFullConfiguration, - _rpc: Box<::std::any::Any + Send + Sync>, + _rpc: Box, _telemetry: Option>, _offchain_workers: Option, ComponentBlock>>>, _telemetry_on_connect_sinks: Arc>>>, @@ -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 + Send + 'static>, + pub on_exit: Box + Send + 'static>, /// Event stream. pub telemetry_connection_sinks: TelemetryOnConnectNotifications, /// Executor to which the hook is spawned. diff --git a/substrate/core/sr-api-macros/src/lib.rs b/substrate/core/sr-api-macros/src/lib.rs index c5f8941002..7399da0794 100644 --- a/substrate/core/sr-api-macros/src/lib.rs +++ b/substrate/core/sr-api-macros/src/lib.rs @@ -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 for Runtime { +/// # fn version() -> client::runtime_api::RuntimeVersion { +/// # unimplemented!() +/// # } +/// # fn execute_block(_block: Block) {} +/// # fn initialize_block(_header: &Header) {} +/// # fn authorities() -> Vec> { unimplemented!() } +/// # } +/// /// impl self::Balance 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); /// } diff --git a/substrate/core/sr-api-macros/tests/decl_and_impl.rs b/substrate/core/sr-api-macros/tests/decl_and_impl.rs index 51f95d51b1..44db8021d4 100644 --- a/substrate/core/sr-api-macros/tests/decl_and_impl.rs +++ b/substrate/core/sr-api-macros/tests/decl_and_impl.rs @@ -122,7 +122,7 @@ fn check_runtime_api_versions_contains() { #[test] fn check_runtime_api_versions() { - check_runtime_api_versions_contains::>(); - check_runtime_api_versions_contains::>(); - check_runtime_api_versions_contains::>(); + check_runtime_api_versions_contains::>(); + check_runtime_api_versions_contains::>(); + check_runtime_api_versions_contains::>(); } diff --git a/substrate/core/sr-io/with_std.rs b/substrate/core/sr-io/with_std.rs index 01e7614de6..0ba833bd9f 100644 --- a/substrate/core/sr-io/with_std.rs +++ b/substrate/core/sr-io/with_std.rs @@ -251,7 +251,7 @@ impl HashingApi for () { } } -fn with_offchain(f: impl FnOnce(&mut offchain::Externalities) -> R, msg: &'static str) -> R { +fn with_offchain(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>(ext: &mut Externalities, f: F) -> R { +pub fn with_externalities R>(ext: &mut dyn Externalities, f: F) -> R { ext::using(ext, f) } diff --git a/substrate/core/sr-primitives/src/generic/mod.rs b/substrate/core/sr-primitives/src/generic/mod.rs index 3d7682407e..89c4291d79 100644 --- a/substrate/core/sr-primitives/src/generic/mod.rs +++ b/substrate/core/sr-primitives/src/generic/mod.rs @@ -44,8 +44,8 @@ use rstd::prelude::*; fn encode_with_vec_prefix)>(encoder: F) -> Vec { let size = ::rstd::mem::size_of::(); 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); diff --git a/substrate/core/state-machine/src/basic.rs b/substrate/core/state-machine/src/basic.rs index 0eb0b84b27..e9939711f1 100644 --- a/substrate/core/state-machine/src/basic.rs +++ b/substrate/core/state-machine/src/basic.rs @@ -156,7 +156,7 @@ impl Externalities 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; + let ext = &mut ext as &mut dyn Externalities; 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; + let ext = &mut ext as &mut dyn Externalities; let code = vec![1, 2, 3]; ext.set_storage(CODE.to_vec(), code.clone()); diff --git a/substrate/core/state-machine/src/changes_trie/mod.rs b/substrate/core/state-machine/src/changes_trie/mod.rs index 15ea1b474f..7dc95fb5a7 100644 --- a/substrate/core/state-machine/src/changes_trie/mod.rs +++ b/substrate/core/state-machine/src/changes_trie/mod.rs @@ -112,7 +112,7 @@ pub trait Storage: RootsStorage { } /// Changes trie storage -> trie backend essence adapter. -pub struct TrieBackendStorageAdapter<'a, H: Hasher, Number: BlockNumber>(pub &'a Storage); +pub struct TrieBackendStorageAdapter<'a, H: Hasher, Number: BlockNumber>(pub &'a dyn Storage); impl<'a, H: Hasher, N: BlockNumber> crate::TrieBackendStorage for TrieBackendStorageAdapter<'a, H, N> { type Overlay = trie::MemoryDB; diff --git a/substrate/core/state-machine/src/ext.rs b/substrate/core/state-machine/src/ext.rs index 6ec1ce77e6..5a0daeb348 100644 --- a/substrate/core/state-machine/src/ext.rs +++ b/substrate/core/state-machine/src/ext.rs @@ -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 _) } } diff --git a/substrate/core/state-machine/src/lib.rs b/substrate/core/state-machine/src/lib.rs index 9f0e20ce01..93d70423d5 100644 --- a/substrate/core/state-machine/src/lib.rs +++ b/substrate/core/state-machine/src/lib.rs @@ -222,7 +222,7 @@ pub trait Externalities { fn storage_changes_root(&mut self, parent: H::Out) -> Result, ()> 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, B::Transaction, Option>), Box> { + ) -> Result<(Vec, B::Transaction, Option>), Box> { // 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, compute_tx: bool, mut native_call: Option, - ) -> Result<(NativeOrEncoded, Option, Option>), Box> where + ) -> Result<(NativeOrEncoded, Option, Option>), Box> where R: Decode + Encode + PartialEq, NC: FnOnce() -> result::Result + UnwindSafe, Handler: FnOnce( @@ -674,7 +674,7 @@ pub fn prove_execution( exec: &Exec, method: &str, call_data: &[u8], -) -> Result<(Vec, Vec>), Box> +) -> Result<(Vec, Vec>), Box> where B: Backend, 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)?; + .ok_or_else(|| Box::new(ExecutionError::UnableToGenerateProof) as Box)?; prove_execution_on_trie_backend(trie_backend, overlay, exec, method, call_data) } @@ -701,7 +701,7 @@ pub fn prove_execution_on_trie_backend( exec: &Exec, method: &str, call_data: &[u8], -) -> Result<(Vec, Vec>), Box> +) -> Result<(Vec, Vec>), Box> where S: trie_backend_essence::TrieBackendStorage, H: Hasher, @@ -736,7 +736,7 @@ pub fn execution_proof_check( exec: &Exec, method: &str, call_data: &[u8], -) -> Result, Box> +) -> Result, Box> where H: Hasher, Exec: CodeExecutor, @@ -753,7 +753,7 @@ pub fn execution_proof_check_on_trie_backend( exec: &Exec, method: &str, call_data: &[u8], -) -> Result, Box> +) -> Result, Box> where H: Hasher, Exec: CodeExecutor, @@ -780,7 +780,7 @@ where pub fn prove_read( mut backend: B, key: &[u8] -) -> Result<(Option>, Vec>), Box> +) -> Result<(Option>, Vec>), Box> where B: Backend, H: Hasher, @@ -788,7 +788,7 @@ where { let trie_backend = backend.as_trie_backend() .ok_or_else( - ||Box::new(ExecutionError::UnableToGenerateProof) as Box + ||Box::new(ExecutionError::UnableToGenerateProof) as Box )?; prove_read_on_trie_backend(trie_backend, key) } @@ -798,14 +798,14 @@ pub fn prove_child_read( mut backend: B, storage_key: &[u8], key: &[u8], -) -> Result<(Option>, Vec>), Box> +) -> Result<(Option>, Vec>), Box> where B: Backend, H: Hasher, H::Out: Ord { let trie_backend = backend.as_trie_backend() - .ok_or_else(|| Box::new(ExecutionError::UnableToGenerateProof) as Box)?; + .ok_or_else(|| Box::new(ExecutionError::UnableToGenerateProof) as Box)?; prove_child_read_on_trie_backend(trie_backend, storage_key, key) } @@ -814,14 +814,14 @@ where pub fn prove_read_on_trie_backend( trie_backend: &TrieBackend, key: &[u8] -) -> Result<(Option>, Vec>), Box> +) -> Result<(Option>, Vec>), Box> where S: trie_backend_essence::TrieBackendStorage, 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)?; + let result = proving_backend.storage(key).map_err(|e| Box::new(e) as Box)?; Ok((result, proving_backend.extract_proof())) } @@ -830,15 +830,14 @@ pub fn prove_child_read_on_trie_backend( trie_backend: &TrieBackend, storage_key: &[u8], key: &[u8] -) -> Result<(Option>, Vec>), Box> +) -> Result<(Option>, Vec>), Box> where S: trie_backend_essence::TrieBackendStorage, 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)?; + let result = proving_backend.child_storage(storage_key, key).map_err(|e| Box::new(e) as Box)?; Ok((result, proving_backend.extract_proof())) } @@ -847,7 +846,7 @@ pub fn read_proof_check( root: H::Out, proof: Vec>, key: &[u8], -) -> Result>, Box> +) -> Result>, Box> where H: Hasher, H::Out: Ord @@ -862,7 +861,7 @@ pub fn read_child_proof_check( proof: Vec>, storage_key: &[u8], key: &[u8], -) -> Result>, Box> +) -> Result>, Box> where H: Hasher, H::Out: Ord @@ -876,12 +875,12 @@ where pub fn read_proof_check_on_proving_backend( proving_backend: &TrieBackend, H>, key: &[u8], -) -> Result>, Box> +) -> Result>, Box> where H: Hasher, H::Out: Ord { - proving_backend.storage(key).map_err(|e| Box::new(e) as Box) + proving_backend.storage(key).map_err(|e| Box::new(e) as Box) } /// Check child storage read proof on pre-created proving backend. @@ -889,20 +888,24 @@ pub fn read_child_proof_check_on_proving_backend( proving_backend: &TrieBackend, H>, storage_key: &[u8], key: &[u8], -) -> Result>, Box> +) -> Result>, Box> where H: Hasher, H::Out: Ord { - proving_backend.child_storage(storage_key, key).map_err(|e| Box::new(e) as Box) + proving_backend.child_storage(storage_key, key).map_err(|e| Box::new(e) as Box) } /// 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>, final_check: bool) -> Result<(), Box> { +pub(crate) fn set_changes_trie_config( + overlay: &mut OverlayedChanges, + config: Option>, + final_check: bool, +) -> Result<(), Box> { 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)?), + .ok_or_else(|| Box::new("Failed to decode changes trie configuration".to_owned()) as Box)?), 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(overlay: &OverlayedChanges, backend: &B, key: &[u8]) - -> Result>, Box> + -> Result>, Box> where H: Hasher, - B: Backend, { 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), + None => backend + .storage(key) + .map_err(|err| Box::new(ExecutionError::Backend(format!("{}", err))) as Box), } } diff --git a/substrate/core/state-machine/src/proving_backend.rs b/substrate/core/state-machine/src/proving_backend.rs index f9472ed747..60178ff899 100644 --- a/substrate/core/state-machine/src/proving_backend.rs +++ b/substrate/core/state-machine/src/proving_backend.rs @@ -193,17 +193,17 @@ impl<'a, S, H> Backend for ProvingBackend<'a, S, H> pub fn create_proof_check_backend( root: H::Out, proof: Vec> -) -> Result, H>, Box> +) -> Result, H>, Box> where H: Hasher, { let db = create_proof_check_backend_storage(proof); - if !db.contains(&root, &[]) { - return Err(Box::new(ExecutionError::InvalidProof) as Box); + 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. diff --git a/substrate/core/state-machine/src/testing.rs b/substrate/core/state-machine/src/testing.rs index 3934e726af..68b9d28752 100644 --- a/substrate/core/state-machine/src/testing.rs +++ b/substrate/core/state-machine/src/testing.rs @@ -37,7 +37,7 @@ pub struct TestExternalities { overlay: OverlayedChanges, backend: InMemory, changes_trie_storage: ChangesTrieInMemoryStorage, - offchain: Option>, + offchain: Option>, } impl TestExternalities { @@ -234,7 +234,7 @@ impl Externalities for TestExternalities )?.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 _) diff --git a/substrate/core/state-machine/src/trie_backend_essence.rs b/substrate/core/state-machine/src/trie_backend_essence.rs index 89a5b42a84..fc30f94f05 100644 --- a/substrate/core/state-machine/src/trie_backend_essence.rs +++ b/substrate/core/state-machine/src/trie_backend_essence.rs @@ -153,8 +153,8 @@ impl<'a, > hash_db::AsPlainDB for Ephemeral<'a, S, H> { - fn as_plain_db<'b>(&'b self) -> &'b (hash_db::PlainDB + 'b) { self } - fn as_plain_db_mut<'b>(&'b mut self) -> &'b mut (hash_db::PlainDB + 'b) { self } + fn as_plain_db<'b>(&'b self) -> &'b (dyn hash_db::PlainDB + 'b) { self } + fn as_plain_db_mut<'b>(&'b mut self) -> &'b mut (dyn hash_db::PlainDB + 'b) { self } } impl<'a, @@ -163,8 +163,8 @@ impl<'a, > hash_db::AsHashDB for Ephemeral<'a, S, H> { - fn as_hash_db<'b>(&'b self) -> &'b (hash_db::HashDB + 'b) { self } - fn as_hash_db_mut<'b>(&'b mut self) -> &'b mut (hash_db::HashDB + 'b) { self } + fn as_hash_db<'b>(&'b self) -> &'b (dyn hash_db::HashDB + 'b) { self } + fn as_hash_db_mut<'b>(&'b mut self) -> &'b mut (dyn hash_db::HashDB + 'b) { self } } impl<'a, S: TrieBackendStorage, H: Hasher> Ephemeral<'a, S, H> { @@ -275,7 +275,7 @@ pub trait TrieBackendStorage: Send + Sync { } // This implementation is used by normal storage trie clients. -impl TrieBackendStorage for Arc> { +impl TrieBackendStorage for Arc> { type Overlay = PrefixedMemoryDB; fn get(&self, key: &H::Out, prefix: &[u8]) -> Result, String> { diff --git a/substrate/core/telemetry/src/lib.rs b/substrate/core/telemetry/src/lib.rs index 16bc69ec00..3f980c5929 100644 --- a/substrate/core/telemetry/src/lib.rs +++ b/substrate/core/telemetry/src/lib.rs @@ -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, + pub on_connect: Box, } /// 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>>, - on_connect: Arc>, + on_connect: Arc>, url: String, } @@ -180,7 +180,7 @@ impl Connection { fn new( out: ws::Sender, out_sync: Arc>>, - on_connect: Arc>, + on_connect: Arc>, url: String ) -> Self { Connection { diff --git a/substrate/core/transaction-pool/graph/src/error.rs b/substrate/core/transaction-pool/graph/src/error.rs index acf3fa4514..07e0324354 100644 --- a/substrate/core/transaction-pool/graph/src/error.rs +++ b/substrate/core/transaction-pool/graph/src/error.rs @@ -35,7 +35,7 @@ pub enum Error { TemporarilyBanned, /// The transaction is already in the pool. #[display(fmt="[{:?}] Already imported", _0)] - AlreadyImported(Box), + AlreadyImported(Box), /// The transaction cannot be imported cause it's a replacement and has too low priority. #[display(fmt="Too low priority ({} > {})", old, new)] TooLowPriority { diff --git a/substrate/core/trie/src/lib.rs b/substrate/core/trie/src/lib.rs index 1322038d78..6298f10bf4 100644 --- a/substrate/core/trie/src/lib.rs +++ b/substrate/core/trie/src/lib.rs @@ -43,9 +43,9 @@ pub type TrieError = trie_db::TrieError; pub trait AsHashDB: hash_db::AsHashDB {} impl> AsHashDB for T {} /// As in `hash_db`, but less generic, trait exposed. -pub type HashDB<'a, H> = hash_db::HashDB + 'a; +pub type HashDB<'a, H> = dyn hash_db::HashDB + 'a; /// As in `hash_db`, but less generic, trait exposed. -pub type PlainDB<'a, K> = hash_db::PlainDB + 'a; +pub type PlainDB<'a, K> = dyn hash_db::PlainDB + 'a; /// As in `memory_db::MemoryDB` that uses prefixed storage key scheme. pub type PrefixedMemoryDB = memory_db::MemoryDB, 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, + db: &'db mut dyn HashDB, root: &'db mut ::Out, v: &[(Vec, Vec)] ) -> TrieDBMut<'db, Blake2Hasher> { diff --git a/substrate/core/trie/src/node_header.rs b/substrate/core/trie/src/node_header.rs index 4f7617c068..2c01189f8a 100644 --- a/substrate/core/trie/src/node_header.rs +++ b/substrate/core/trie/src/node_header.rs @@ -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), diff --git a/substrate/core/trie/src/trie_stream.rs b/substrate/core/trie/src/trie_stream.rs index 123ab1ea16..913cff2c5a 100644 --- a/substrate/core/trie/src/trie_stream.rs +++ b/substrate/core/trie/src/trie_stream.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -//! `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(&mut self, other: Self) { let data = other.out(); match data.len() { - 0...31 => { + 0..=31 => { data.encode_to(&mut self.buffer) }, _ => { diff --git a/substrate/core/util/fork-tree/src/lib.rs b/substrate/core/util/fork-tree/src/lib.rs index cba5a1535b..4b6745a354 100644 --- a/substrate/core/util/fork-tree/src/lib.rs +++ b/substrate/core/util/fork-tree/src/lib.rs @@ -52,7 +52,7 @@ impl std::error::Error for Error { } } - fn cause(&self) -> Option<&std::error::Error> { + fn cause(&self) -> Option<&dyn std::error::Error> { None } } diff --git a/substrate/srml/aura/src/lib.rs b/substrate/srml/aura/src/lib.rs index bc46e98ec2..597618c142 100644 --- a/substrate/srml/aura/src/lib.rs +++ b/substrate/srml/aura/src/lib.rs @@ -150,7 +150,6 @@ impl ProvideInherentData for InherentDataProvider { } fn error_to_string(&self, error: &[u8]) -> Option { - use parity_codec::Decode; RuntimeString::decode(&mut &error[..]).map(Into::into) } } diff --git a/substrate/srml/contract/src/exec.rs b/substrate/srml/contract/src/exec.rs index 1ab59fa0c2..7a16c9d60d 100644 --- a/substrate/srml/contract/src/exec.rs +++ b/substrate/srml/contract/src/exec.rs @@ -703,7 +703,7 @@ mod tests { } #[derive(Clone)] - struct MockExecutable<'a>(Rc VmExecResult + 'a>); + struct MockExecutable<'a>(Rc VmExecResult + 'a>); impl<'a> MockExecutable<'a> { fn new(f: impl Fn(MockCtx) -> VmExecResult + 'a) -> Self { diff --git a/substrate/srml/contract/src/tests.rs b/substrate/srml/contract/src/tests.rs index 29fc1d3a6d..7a19fdb1d6 100644 --- a/substrate/srml/contract/src/tests.rs +++ b/substrate/srml/contract/src/tests.rs @@ -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!(>::get_storage(&DirectAccountDb, &1, Some(&trie_id1), key1).is_none()); - assert!(>::get_storage(&DirectAccountDb, &1, Some(&trie_id1), key2).is_none()); + assert!(>::get_storage(&DirectAccountDb, &1, Some(&trie_id1), key1).is_none()); + assert!(>::get_storage(&DirectAccountDb, &1, Some(&trie_id1), key2).is_none()); assert_eq!( - >::get_storage(&DirectAccountDb, &2, Some(&trie_id2), key1), + >::get_storage(&DirectAccountDb, &2, Some(&trie_id2), key1), Some(b"3".to_vec()) ); assert_eq!( - >::get_storage(&DirectAccountDb, &2, Some(&trie_id2), key2), + >::get_storage(&DirectAccountDb, &2, Some(&trie_id2), key2), Some(b"4".to_vec()) ); } diff --git a/substrate/srml/indices/src/address.rs b/substrate/srml/indices/src/address.rs index 123b8bca89..c76585d216 100644 --- a/substrate/srml/indices/src/address.rs +++ b/substrate/srml/indices/src/address.rs @@ -64,7 +64,7 @@ impl Decode for Address where { fn decode(input: &mut I) -> Option { 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 )), diff --git a/substrate/subkey/src/vanity.rs b/substrate/subkey/src/vanity.rs index 400b3bae82..2399197e99 100644 --- a/substrate/subkey/src/vanity.rs +++ b/substrate/subkey/src/vanity.rs @@ -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, } }