From 1700873f48c94d5c191c836d380a94cf40d46923 Mon Sep 17 00:00:00 2001 From: adria0 Date: Wed, 29 Jul 2020 10:36:15 +0200 Subject: [PATCH] Fix warnings: dyn --- accounts/ethstore/cli/src/main.rs | 2 +- accounts/ethstore/src/accounts_dir/disk.rs | 6 +- accounts/ethstore/src/accounts_dir/mod.rs | 8 +- accounts/ethstore/src/accounts_dir/vault.rs | 2 +- accounts/ethstore/src/ethstore.rs | 16 +-- accounts/ethstore/src/import.rs | 9 +- accounts/ethstore/src/secret_store.rs | 2 +- accounts/hw/src/trezor.rs | 2 +- accounts/src/lib.rs | 4 +- cli-signer/rpc-client/src/lib.rs | 2 +- ethcore/blockchain/src/blockchain.rs | 22 ++--- ethcore/db/src/db.rs | 22 ++--- ethcore/evm/src/factory.rs | 2 +- ethcore/evm/src/interpreter/gasometer.rs | 6 +- ethcore/evm/src/interpreter/informant.rs | 2 +- ethcore/evm/src/interpreter/memory.rs | 6 +- ethcore/evm/src/interpreter/mod.rs | 20 ++-- ethcore/light/src/cht.rs | 2 +- ethcore/light/src/client/fetch.rs | 8 +- ethcore/light/src/client/header_chain.rs | 6 +- ethcore/light/src/client/mod.rs | 36 ++++--- ethcore/light/src/client/service.rs | 6 +- ethcore/light/src/net/context.rs | 8 +- ethcore/light/src/net/load_timer.rs | 4 +- ethcore/light/src/net/mod.rs | 85 +++++++++------- ethcore/light/src/on_demand/mod.rs | 24 ++--- ethcore/light/src/on_demand/request.rs | 6 +- ethcore/light/src/on_demand/tests.rs | 2 +- ethcore/light/src/transaction_queue.rs | 2 +- ethcore/node-filter/src/lib.rs | 6 +- ethcore/private-tx/src/encryptor.rs | 4 +- ethcore/private-tx/src/error.rs | 2 +- ethcore/private-tx/src/lib.rs | 18 ++-- ethcore/service/src/service.rs | 16 +-- ethcore/src/account_db.rs | 40 ++++---- ethcore/src/block.rs | 22 ++--- ethcore/src/client/ancient_import.rs | 8 +- ethcore/src/client/client.rs | 22 ++--- ethcore/src/client/io_message.rs | 2 +- ethcore/src/client/test_client.rs | 6 +- ethcore/src/client/trace.rs | 4 +- ethcore/src/client/traits.rs | 12 +-- ethcore/src/engines/authority_round/mod.rs | 47 +++++---- ethcore/src/engines/basic_authority.rs | 12 +-- ethcore/src/engines/clique/mod.rs | 14 +-- ethcore/src/engines/mod.rs | 24 ++--- ethcore/src/engines/null_engine.rs | 2 +- ethcore/src/engines/signer.rs | 2 +- ethcore/src/engines/validator_set/contract.rs | 4 +- ethcore/src/engines/validator_set/mod.rs | 4 +- ethcore/src/engines/validator_set/multi.rs | 15 +-- .../engines/validator_set/safe_contract.rs | 4 +- .../src/engines/validator_set/simple_list.rs | 4 +- ethcore/src/ethereum/ethash.rs | 2 +- ethcore/src/executive.rs | 4 +- ethcore/src/factory.rs | 2 +- ethcore/src/machine/impls.rs | 6 +- ethcore/src/miner/miner.rs | 12 +-- ethcore/src/miner/pool_client.rs | 8 +- ethcore/src/miner/stratum.rs | 2 +- ethcore/src/pod_account.rs | 2 +- ethcore/src/snapshot/consensus/authority.rs | 16 +-- ethcore/src/snapshot/consensus/mod.rs | 10 +- ethcore/src/snapshot/consensus/work.rs | 12 +-- ethcore/src/snapshot/service.rs | 24 ++--- ethcore/src/snapshot/tests/helpers.rs | 10 +- ethcore/src/snapshot/watcher.rs | 4 +- ethcore/src/spec/spec.rs | 4 +- ethcore/src/state/account.rs | 20 ++-- ethcore/src/state/backend.rs | 26 ++--- ethcore/src/state/mod.rs | 4 +- ethcore/src/state_db.rs | 16 +-- ethcore/src/test_helpers.rs | 18 ++-- ethcore/src/trace/db.rs | 4 +- ethcore/src/verification/canon_verifier.rs | 4 +- ethcore/src/verification/mod.rs | 2 +- ethcore/src/verification/noop_verifier.rs | 8 +- ethcore/src/verification/queue/kind.rs | 12 +-- ethcore/src/verification/queue/mod.rs | 6 +- ethcore/src/verification/verification.rs | 24 ++--- ethcore/src/verification/verifier.rs | 4 +- ethcore/sync/src/api.rs | 48 ++++----- ethcore/sync/src/block_sync.rs | 16 +-- ethcore/sync/src/blocks.rs | 8 +- ethcore/sync/src/chain/handler.rs | 32 +++--- ethcore/sync/src/chain/mod.rs | 77 ++++++++------- ethcore/sync/src/chain/propagator.rs | 31 +++--- ethcore/sync/src/chain/requester.rs | 18 ++-- ethcore/sync/src/chain/supplier.rs | 20 ++-- ethcore/sync/src/light_sync/mod.rs | 16 +-- ethcore/sync/src/snapshot.rs | 2 +- ethcore/sync/src/sync_io.rs | 20 ++-- ethcore/sync/src/tests/consensus.rs | 4 +- ethcore/sync/src/tests/helpers.rs | 4 +- ethcore/sync/src/tests/private.rs | 4 +- ethcore/vm/src/error.rs | 4 +- ethcore/vm/src/lib.rs | 6 +- ethcore/wasm/run/src/runner.rs | 2 +- ethcore/wasm/src/lib.rs | 4 +- ethcore/wasm/src/runtime.rs | 4 +- miner/local-store/src/lib.rs | 8 +- miner/src/pool/listener.rs | 2 +- miner/src/pool/local_transactions.rs | 2 +- miner/src/pool/queue.rs | 2 +- miner/src/pool/replace.rs | 2 +- miner/stratum/src/lib.rs | 4 +- parity-clib/src/lib.rs | 8 +- parity/account_utils.rs | 8 +- parity/db/rocksdb/mod.rs | 17 ++-- parity/informant.rs | 6 +- parity/ipfs.rs | 2 +- parity/light_helpers/epoch_fetch.rs | 6 +- parity/modules.rs | 22 ++--- parity/rpc_apis.rs | 10 +- parity/run.rs | 14 +-- parity/secretstore.rs | 99 ++++++++++--------- parity/whisper.rs | 7 +- rpc/src/v1/helpers/deprecated.rs | 2 +- rpc/src/v1/helpers/dispatch/full.rs | 2 +- rpc/src/v1/helpers/dispatch/light.rs | 8 +- rpc/src/v1/helpers/dispatch/mod.rs | 4 +- .../v1/helpers/dispatch/prospective_signer.rs | 4 +- rpc/src/v1/helpers/external_signer/mod.rs | 2 +- .../helpers/external_signer/signing_queue.rs | 2 +- rpc/src/v1/helpers/light_fetch.rs | 12 +-- rpc/src/v1/helpers/subscription_manager.rs | 2 +- rpc/src/v1/impls/eth.rs | 4 +- rpc/src/v1/impls/eth_pubsub.rs | 2 +- rpc/src/v1/impls/light/eth.rs | 4 +- rpc/src/v1/impls/light/parity_set.rs | 6 +- rpc/src/v1/impls/parity.rs | 12 +-- rpc/src/v1/impls/parity_set.rs | 4 +- rpc/src/v1/impls/signer.rs | 6 +- rpc/src/v1/impls/signing.rs | 4 +- rpc/src/v1/impls/signing_unsafe.rs | 4 +- rpc/src/v1/tests/helpers/miner_service.rs | 4 +- rpc/src/v1/tests/mocked/manage_network.rs | 2 +- rpc/src/v1/tests/mocked/parity.rs | 2 +- rpc/src/v1/tests/mocked/parity_set.rs | 2 +- secret-store/src/key_server.rs | 20 ++-- .../key_version_negotiation_session.rs | 6 +- .../servers_set_change_session.rs | 14 +-- .../admin_sessions/sessions_queue.rs | 2 +- .../admin_sessions/share_add_session.rs | 8 +- .../admin_sessions/share_change_session.rs | 12 +-- .../client_sessions/decryption_session.rs | 10 +- .../client_sessions/encryption_session.rs | 10 +- .../client_sessions/generation_session.rs | 8 +- .../client_sessions/signing_session_ecdsa.rs | 12 +-- .../signing_session_schnorr.rs | 12 +-- .../src/key_server_cluster/cluster.rs | 68 +++++++------ .../key_server_cluster/cluster_connections.rs | 8 +- .../cluster_connections_net.rs | 16 +-- .../cluster_message_processor.rs | 20 ++-- .../key_server_cluster/cluster_sessions.rs | 20 ++-- .../cluster_sessions_creator.rs | 23 ++--- .../key_server_cluster/connection_trigger.rs | 18 ++-- .../connection_trigger_with_migration.rs | 14 +-- .../src/key_server_cluster/io/deadline.rs | 2 +- .../src/key_server_cluster/io/handshake.rs | 10 +- .../key_server_cluster/jobs/key_access_job.rs | 6 +- .../jobs/unknown_sessions_job.rs | 6 +- .../net/accept_connection.rs | 2 +- .../src/key_server_cluster/net/connect.rs | 4 +- secret-store/src/key_server_set.rs | 12 +-- secret-store/src/key_storage.rs | 14 +-- secret-store/src/lib.rs | 30 +++--- secret-store/src/listener/http_listener.rs | 8 +- secret-store/src/listener/mod.rs | 4 +- secret-store/src/listener/service_contract.rs | 32 +++--- .../listener/service_contract_aggregate.rs | 12 +-- .../src/listener/service_contract_listener.rs | 36 +++---- secret-store/src/trusted_client.rs | 8 +- updater/hash-fetch/src/client.rs | 8 +- updater/hash-fetch/src/urlhint.rs | 12 ++- updater/src/updater.rs | 18 ++-- util/fetch/src/client.rs | 6 +- util/io/src/service_mio.rs | 21 ++-- util/io/src/service_non_mio.rs | 7 +- util/io/src/worker.rs | 2 +- util/journaldb/src/archivedb.rs | 8 +- util/journaldb/src/as_hash_db_impls.rs | 30 +++--- util/journaldb/src/earlymergedb.rs | 16 +-- util/journaldb/src/lib.rs | 4 +- util/journaldb/src/overlaydb.rs | 4 +- util/journaldb/src/overlayrecentdb.rs | 10 +- util/journaldb/src/refcounteddb.rs | 8 +- util/journaldb/src/traits.rs | 6 +- util/migration-rocksdb/src/lib.rs | 6 +- util/network-devp2p/src/host.rs | 10 +- util/network-devp2p/src/service.rs | 10 +- util/network-devp2p/tests/tests.rs | 10 +- util/network/src/lib.rs | 12 +-- util/registrar/src/registrar.rs | 8 +- util/rlp-compress/src/lib.rs | 4 +- whisper/cli/src/main.rs | 6 +- whisper/src/net/mod.rs | 20 ++-- whisper/src/rpc/filter.rs | 4 +- 198 files changed, 1180 insertions(+), 1072 deletions(-) diff --git a/accounts/ethstore/cli/src/main.rs b/accounts/ethstore/cli/src/main.rs index 2056fb73b..214f73376 100644 --- a/accounts/ethstore/cli/src/main.rs +++ b/accounts/ethstore/cli/src/main.rs @@ -164,7 +164,7 @@ fn main() { } } -fn key_dir(location: &str, password: Option) -> Result, Error> { +fn key_dir(location: &str, password: Option) -> Result, Error> { let dir: RootDiskDirectory = match location { "geth" => RootDiskDirectory::create(dir::geth(false))?, "geth-test" => RootDiskDirectory::create(dir::geth(true))?, diff --git a/accounts/ethstore/src/accounts_dir/disk.rs b/accounts/ethstore/src/accounts_dir/disk.rs index 3c08b860c..e6695a8d5 100644 --- a/accounts/ethstore/src/accounts_dir/disk.rs +++ b/accounts/ethstore/src/accounts_dir/disk.rs @@ -335,7 +335,7 @@ where Some(&self.path) } - fn as_vault_provider(&self) -> Option<&VaultKeyDirectoryProvider> { + fn as_vault_provider(&self) -> Option<&dyn VaultKeyDirectoryProvider> { Some(self) } @@ -348,12 +348,12 @@ impl VaultKeyDirectoryProvider for DiskDirectory where T: KeyFileManager, { - fn create(&self, name: &str, key: VaultKey) -> Result, Error> { + fn create(&self, name: &str, key: VaultKey) -> Result, Error> { let vault_dir = VaultDiskDirectory::create(&self.path, name, key)?; Ok(Box::new(vault_dir)) } - fn open(&self, name: &str, key: VaultKey) -> Result, Error> { + fn open(&self, name: &str, key: VaultKey) -> Result, Error> { let vault_dir = VaultDiskDirectory::at(&self.path, name, key)?; Ok(Box::new(vault_dir)) } diff --git a/accounts/ethstore/src/accounts_dir/mod.rs b/accounts/ethstore/src/accounts_dir/mod.rs index da682c41e..1926cdc06 100644 --- a/accounts/ethstore/src/accounts_dir/mod.rs +++ b/accounts/ethstore/src/accounts_dir/mod.rs @@ -60,7 +60,7 @@ pub trait KeyDirectory: Send + Sync { None } /// Return vault provider, if available - fn as_vault_provider(&self) -> Option<&VaultKeyDirectoryProvider> { + fn as_vault_provider(&self) -> Option<&dyn VaultKeyDirectoryProvider> { None } /// Unique representation of directory account collection @@ -70,9 +70,9 @@ pub trait KeyDirectory: Send + Sync { /// Vaults provider pub trait VaultKeyDirectoryProvider { /// Create new vault with given key - fn create(&self, name: &str, key: VaultKey) -> Result, Error>; + fn create(&self, name: &str, key: VaultKey) -> Result, Error>; /// Open existing vault with given key - fn open(&self, name: &str, key: VaultKey) -> Result, Error>; + fn open(&self, name: &str, key: VaultKey) -> Result, Error>; /// List all vaults fn list_vaults(&self) -> Result, Error>; /// Get vault meta @@ -82,7 +82,7 @@ pub trait VaultKeyDirectoryProvider { /// Vault directory pub trait VaultKeyDirectory: KeyDirectory { /// Cast to `KeyDirectory` - fn as_key_directory(&self) -> &KeyDirectory; + fn as_key_directory(&self) -> &dyn KeyDirectory; /// Vault name fn name(&self) -> &str; /// Get vault key diff --git a/accounts/ethstore/src/accounts_dir/vault.rs b/accounts/ethstore/src/accounts_dir/vault.rs index 5041a4439..c909b072f 100644 --- a/accounts/ethstore/src/accounts_dir/vault.rs +++ b/accounts/ethstore/src/accounts_dir/vault.rs @@ -146,7 +146,7 @@ impl VaultDiskDirectory { } impl VaultKeyDirectory for VaultDiskDirectory { - fn as_key_directory(&self) -> &KeyDirectory { + fn as_key_directory(&self) -> &dyn KeyDirectory { self } diff --git a/accounts/ethstore/src/ethstore.rs b/accounts/ethstore/src/ethstore.rs index cd78c5342..4846ec1a7 100644 --- a/accounts/ethstore/src/ethstore.rs +++ b/accounts/ethstore/src/ethstore.rs @@ -52,13 +52,13 @@ pub struct EthStore { impl EthStore { /// Open a new accounts store with given key directory backend. - pub fn open(directory: Box) -> Result { + pub fn open(directory: Box) -> Result { Self::open_with_iterations(directory, *KEY_ITERATIONS) } /// Open a new account store with given key directory backend and custom number of iterations. pub fn open_with_iterations( - directory: Box, + directory: Box, iterations: NonZeroU32, ) -> Result { Ok(EthStore { @@ -278,7 +278,7 @@ impl SecretStore for EthStore { fn copy_account( &self, - new_store: &SimpleSecretStore, + new_store: &dyn SimpleSecretStore, new_vault: SecretVaultRef, account: &StoreAccountRef, password: &Password, @@ -367,11 +367,11 @@ impl SecretStore for EthStore { /// Similar to `EthStore` but may store many accounts (with different passwords) for the same `Address` pub struct EthMultiStore { - dir: Box, + dir: Box, iterations: NonZeroU32, // order lock: cache, then vaults cache: RwLock>>, - vaults: Mutex>>, + vaults: Mutex>>, timestamp: Mutex, } @@ -383,13 +383,13 @@ struct Timestamp { impl EthMultiStore { /// Open new multi-accounts store with given key directory backend. - pub fn open(directory: Box) -> Result { + pub fn open(directory: Box) -> Result { Self::open_with_iterations(directory, *KEY_ITERATIONS) } /// Open new multi-accounts store with given key directory backend and custom number of iterations for new keys. pub fn open_with_iterations( - directory: Box, + directory: Box, iterations: NonZeroU32, ) -> Result { let store = EthMultiStore { @@ -953,7 +953,7 @@ mod tests { } struct RootDiskDirectoryGuard { - pub key_dir: Option>, + pub key_dir: Option>, _path: TempDir, } diff --git a/accounts/ethstore/src/import.rs b/accounts/ethstore/src/import.rs index d8c760069..b6633d438 100644 --- a/accounts/ethstore/src/import.rs +++ b/accounts/ethstore/src/import.rs @@ -22,7 +22,7 @@ use ethkey::Address; use Error; /// Import an account from a file. -pub fn import_account(path: &Path, dst: &KeyDirectory) -> Result { +pub fn import_account(path: &Path, dst: &dyn KeyDirectory) -> Result { let key_manager = DiskKeyFileManager::default(); let existing_accounts = dst .load()? @@ -45,7 +45,10 @@ pub fn import_account(path: &Path, dst: &KeyDirectory) -> Result } /// Import all accounts from one directory to the other. -pub fn import_accounts(src: &KeyDirectory, dst: &KeyDirectory) -> Result, Error> { +pub fn import_accounts( + src: &dyn KeyDirectory, + dst: &dyn KeyDirectory, +) -> Result, Error> { let accounts = src.load()?; let existing_accounts = dst .load()? @@ -74,7 +77,7 @@ pub fn read_geth_accounts(testnet: bool) -> Vec
{ /// Import specific `desired` accounts from the Geth keystore into `dst`. pub fn import_geth_accounts( - dst: &KeyDirectory, + dst: &dyn KeyDirectory, desired: HashSet
, testnet: bool, ) -> Result, Error> { diff --git a/accounts/ethstore/src/secret_store.rs b/accounts/ethstore/src/secret_store.rs index 55c7148bf..5d07585fe 100644 --- a/accounts/ethstore/src/secret_store.rs +++ b/accounts/ethstore/src/secret_store.rs @@ -195,7 +195,7 @@ pub trait SecretStore: SimpleSecretStore { /// Copies account between stores and vaults. fn copy_account( &self, - new_store: &SimpleSecretStore, + new_store: &dyn SimpleSecretStore, new_vault: SecretVaultRef, account: &StoreAccountRef, password: &Password, diff --git a/accounts/hw/src/trezor.rs b/accounts/hw/src/trezor.rs index dd185c6e3..cdaa320de 100644 --- a/accounts/hw/src/trezor.rs +++ b/accounts/hw/src/trezor.rs @@ -231,7 +231,7 @@ impl Manager { &self, device: &hidapi::HidDevice, msg_type: MessageType, - msg: &Message, + msg: &dyn Message, ) -> Result { let msg_id = msg_type as u16; let mut message = msg.write_to_bytes()?; diff --git a/accounts/src/lib.rs b/accounts/src/lib.rs index 84fbd1fe3..83c5b90c2 100644 --- a/accounts/src/lib.rs +++ b/accounts/src/lib.rs @@ -77,7 +77,7 @@ pub struct AccountProvider { /// Address book. address_book: RwLock, /// Accounts on disk - sstore: Box, + sstore: Box, /// Accounts unlocked with rolling tokens transient_sstore: EthMultiStore, /// Accounts in hardware wallets. @@ -96,7 +96,7 @@ fn transient_sstore() -> EthMultiStore { impl AccountProvider { /// Creates new account provider. - pub fn new(sstore: Box, settings: AccountProviderSettings) -> Self { + pub fn new(sstore: Box, settings: AccountProviderSettings) -> Self { let mut hardware_store = None; if settings.enable_hardware_wallets { diff --git a/cli-signer/rpc-client/src/lib.rs b/cli-signer/rpc-client/src/lib.rs index 11fdbacc8..47ec502b6 100644 --- a/cli-signer/rpc-client/src/lib.rs +++ b/cli-signer/rpc-client/src/lib.rs @@ -36,7 +36,7 @@ extern crate log; extern crate matches; /// Boxed future response. -pub type BoxFuture = Box + Send>; +pub type BoxFuture = Box + Send>; #[cfg(test)] mod tests { diff --git a/ethcore/blockchain/src/blockchain.rs b/ethcore/blockchain/src/blockchain.rs index 808ef8d62..02cbaf108 100644 --- a/ethcore/blockchain/src/blockchain.rs +++ b/ethcore/blockchain/src/blockchain.rs @@ -68,7 +68,7 @@ use crate::{ /// Database backing `BlockChain`. pub trait BlockChainDB: Send + Sync { /// Generic key value store. - fn key_value(&self) -> &Arc; + fn key_value(&self) -> &Arc; /// Header blooms database. fn blooms(&self) -> &blooms_db::Database; @@ -96,7 +96,7 @@ pub trait BlockChainDB: Send + Sync { /// predefined config. pub trait BlockChainDBHandler: Send + Sync { /// Open the predefined key-value database. - fn open(&self, path: &Path) -> io::Result>; + fn open(&self, path: &Path) -> io::Result>; } /// Interface for querying blocks by hash and by number. @@ -262,7 +262,7 @@ pub struct BlockChain { transaction_addresses: RwLock>, block_receipts: RwLock>, - db: Arc, + db: Arc, cache_man: Mutex>, @@ -576,7 +576,7 @@ impl<'a> Iterator for AncestryWithMetadataIter<'a> { /// Returns epoch transitions. pub struct EpochTransitionIter<'a> { chain: &'a BlockChain, - prefix_iter: Box, Box<[u8]>)> + 'a>, + prefix_iter: Box, Box<[u8]>)> + 'a>, } impl<'a> Iterator for EpochTransitionIter<'a> { @@ -621,7 +621,7 @@ impl<'a> Iterator for EpochTransitionIter<'a> { impl BlockChain { /// Create new instance of blockchain from given Genesis. - pub fn new(config: Config, genesis: &[u8], db: Arc) -> BlockChain { + pub fn new(config: Config, genesis: &[u8], db: Arc) -> BlockChain { // 400 is the average size of the key let cache_man = CacheManager::new(config.pref_cache_size, config.max_cache_size, 400); @@ -1934,11 +1934,11 @@ mod tests { _trace_blooms_dir: TempDir, blooms: blooms_db::Database, trace_blooms: blooms_db::Database, - key_value: Arc, + key_value: Arc, } impl BlockChainDB for TestBlockChainDB { - fn key_value(&self) -> &Arc { + fn key_value(&self) -> &Arc { &self.key_value } @@ -1952,7 +1952,7 @@ mod tests { } /// Creates new test instance of `BlockChainDB` - pub fn new_db() -> Arc { + pub fn new_db() -> Arc { let blooms_dir = TempDir::new("").unwrap(); let trace_blooms_dir = TempDir::new("").unwrap(); @@ -1967,12 +1967,12 @@ mod tests { Arc::new(db) } - fn new_chain(genesis: encoded::Block, db: Arc) -> BlockChain { + fn new_chain(genesis: encoded::Block, db: Arc) -> BlockChain { BlockChain::new(Config::default(), genesis.raw(), db) } fn insert_block( - db: &Arc, + db: &Arc, bc: &BlockChain, block: encoded::Block, receipts: Vec, @@ -1981,7 +1981,7 @@ mod tests { } fn insert_block_commit( - db: &Arc, + db: &Arc, bc: &BlockChain, block: encoded::Block, receipts: Vec, diff --git a/ethcore/db/src/db.rs b/ethcore/db/src/db.rs index 5fc837691..290a22255 100644 --- a/ethcore/db/src/db.rs +++ b/ethcore/db/src/db.rs @@ -92,13 +92,13 @@ pub trait Key { /// Should be used to write value into database. pub trait Writable { /// Writes the value into the database. - fn write(&mut self, col: Option, key: &Key, value: &T) + fn write(&mut self, col: Option, key: &dyn Key, value: &T) where T: rlp::Encodable, R: Deref; /// Deletes key from the databse. - fn delete(&mut self, col: Option, key: &Key) + fn delete(&mut self, col: Option, key: &dyn Key) where T: rlp::Encodable, R: Deref; @@ -107,7 +107,7 @@ pub trait Writable { fn write_with_cache( &mut self, col: Option, - cache: &mut Cache, + cache: &mut dyn Cache, key: K, value: T, policy: CacheUpdatePolicy, @@ -131,7 +131,7 @@ pub trait Writable { fn extend_with_cache( &mut self, col: Option, - cache: &mut Cache, + cache: &mut dyn Cache, values: HashMap, policy: CacheUpdatePolicy, ) where @@ -159,7 +159,7 @@ pub trait Writable { fn extend_with_option_cache( &mut self, col: Option, - cache: &mut Cache>, + cache: &mut dyn Cache>, values: HashMap>, policy: CacheUpdatePolicy, ) where @@ -193,7 +193,7 @@ pub trait Writable { /// Should be used to read values from database. pub trait Readable { /// Returns value for given key. - fn read(&self, col: Option, key: &Key) -> Option + fn read(&self, col: Option, key: &dyn Key) -> Option where T: rlp::Decodable, R: Deref; @@ -243,7 +243,7 @@ pub trait Readable { } /// Returns true if given value exists. - fn exists(&self, col: Option, key: &Key) -> bool + fn exists(&self, col: Option, key: &dyn Key) -> bool where R: Deref; @@ -266,7 +266,7 @@ pub trait Readable { } impl Writable for DBTransaction { - fn write(&mut self, col: Option, key: &Key, value: &T) + fn write(&mut self, col: Option, key: &dyn Key, value: &T) where T: rlp::Encodable, R: Deref, @@ -274,7 +274,7 @@ impl Writable for DBTransaction { self.put(col, &key.key(), &rlp::encode(value)); } - fn delete(&mut self, col: Option, key: &Key) + fn delete(&mut self, col: Option, key: &dyn Key) where T: rlp::Encodable, R: Deref, @@ -284,7 +284,7 @@ impl Writable for DBTransaction { } impl Readable for KVDB { - fn read(&self, col: Option, key: &Key) -> Option + fn read(&self, col: Option, key: &dyn Key) -> Option where T: rlp::Decodable, R: Deref, @@ -294,7 +294,7 @@ impl Readable for KVDB { .map(|v| rlp::decode(&v).expect("decode db value failed")) } - fn exists(&self, col: Option, key: &Key) -> bool + fn exists(&self, col: Option, key: &dyn Key) -> bool where R: Deref, { diff --git a/ethcore/evm/src/factory.rs b/ethcore/evm/src/factory.rs index f9eae766f..1d7363813 100644 --- a/ethcore/evm/src/factory.rs +++ b/ethcore/evm/src/factory.rs @@ -31,7 +31,7 @@ pub struct Factory { impl Factory { /// Create fresh instance of VM /// Might choose implementation depending on supplied gas. - pub fn create(&self, params: ActionParams, schedule: &Schedule, depth: usize) -> Box { + pub fn create(&self, params: ActionParams, schedule: &Schedule, depth: usize) -> Box { match self.evm { VMType::Interpreter => { if Self::can_fit_in_usize(¶ms.gas) { diff --git a/ethcore/evm/src/interpreter/gasometer.rs b/ethcore/evm/src/interpreter/gasometer.rs index acb3fdb1c..93a9f0c13 100644 --- a/ethcore/evm/src/interpreter/gasometer.rs +++ b/ethcore/evm/src/interpreter/gasometer.rs @@ -112,10 +112,10 @@ impl Gasometer { /// it will be the amount of gas that the current context provides to the child context. pub fn requirements( &mut self, - ext: &vm::Ext, + ext: &dyn vm::Ext, instruction: Instruction, info: &InstructionInfo, - stack: &Stack, + stack: &dyn Stack, current_mem_size: usize, ) -> vm::Result> { let schedule = ext.schedule(); @@ -427,7 +427,7 @@ fn calculate_eip1283_sstore_gas( } pub fn handle_eip1283_sstore_clears_refund( - ext: &mut vm::Ext, + ext: &mut dyn vm::Ext, original: &U256, current: &U256, new: &U256, diff --git a/ethcore/evm/src/interpreter/informant.rs b/ethcore/evm/src/interpreter/informant.rs index f5d45eb8d..d9cf37b25 100644 --- a/ethcore/evm/src/interpreter/informant.rs +++ b/ethcore/evm/src/interpreter/informant.rs @@ -96,7 +96,7 @@ mod inner { instruction: Instruction, info: &InstructionInfo, current_gas: &Cost, - stack: &Stack, + stack: &dyn Stack, ) { let time = self.last_instruction.elapsed(); self.last_instruction = Instant::now(); diff --git a/ethcore/evm/src/interpreter/memory.rs b/ethcore/evm/src/interpreter/memory.rs index d834a3065..8c32fa8fa 100644 --- a/ethcore/evm/src/interpreter/memory.rs +++ b/ethcore/evm/src/interpreter/memory.rs @@ -136,7 +136,7 @@ mod tests { #[test] fn test_memory_read_and_write() { // given - let mem: &mut Memory = &mut vec![]; + let mem: &mut dyn Memory = &mut vec![]; mem.resize(0x80 + 32); // when @@ -149,7 +149,7 @@ mod tests { #[test] fn test_memory_read_and_write_byte() { // given - let mem: &mut Memory = &mut vec![]; + let mem: &mut dyn Memory = &mut vec![]; mem.resize(32); // when @@ -163,7 +163,7 @@ mod tests { #[test] fn test_memory_read_slice_and_write_slice() { - let mem: &mut Memory = &mut vec![]; + let mem: &mut dyn Memory = &mut vec![]; mem.resize(32); { diff --git a/ethcore/evm/src/interpreter/mod.rs b/ethcore/evm/src/interpreter/mod.rs index 4ee8c5661..f1c03c0fd 100644 --- a/ethcore/evm/src/interpreter/mod.rs +++ b/ethcore/evm/src/interpreter/mod.rs @@ -192,7 +192,7 @@ pub struct Interpreter { } impl vm::Exec for Interpreter { - fn exec(mut self: Box, ext: &mut vm::Ext) -> vm::ExecTrapResult { + fn exec(mut self: Box, ext: &mut dyn vm::Ext) -> vm::ExecTrapResult { loop { let result = self.step(ext); match result { @@ -213,7 +213,7 @@ impl vm::Exec for Interpreter { } impl vm::ResumeCall for Interpreter { - fn resume_call(mut self: Box, result: MessageCallResult) -> Box { + fn resume_call(mut self: Box, result: MessageCallResult) -> Box { { let this = &mut *self; let (out_off, out_size) = this.resume_output_range.take().expect("Box is obtained from a call opcode; resume_output_range is always set after those opcodes are executed; qed"); @@ -254,7 +254,7 @@ impl vm::ResumeCall for Interpreter { } impl vm::ResumeCreate for Interpreter { - fn resume_create(mut self: Box, result: ContractCreateResult) -> Box { + fn resume_create(mut self: Box, result: ContractCreateResult) -> Box { match result { ContractCreateResult::Created(address, gas_left) => { self.stack.push(address_to_u256(address)); @@ -318,7 +318,7 @@ impl Interpreter { /// Execute a single step on the VM. #[inline(always)] - pub fn step(&mut self, ext: &mut vm::Ext) -> InterpreterResult { + pub fn step(&mut self, ext: &mut dyn vm::Ext) -> InterpreterResult { if self.done { return InterpreterResult::Stopped; } @@ -531,7 +531,7 @@ impl Interpreter { fn verify_instruction( &self, - ext: &vm::Ext, + ext: &dyn vm::Ext, instruction: Instruction, info: &InstructionInfo, ) -> vm::Result<()> { @@ -574,7 +574,7 @@ impl Interpreter { } } - fn mem_written(instruction: Instruction, stack: &Stack) -> Option<(usize, usize)> { + fn mem_written(instruction: Instruction, stack: &dyn Stack) -> Option<(usize, usize)> { let read = |pos| stack.peek(pos).low_u64() as usize; let written = match instruction { instructions::MSTORE | instructions::MLOAD => Some((read(0), 32)), @@ -594,7 +594,7 @@ impl Interpreter { } } - fn store_written(instruction: Instruction, stack: &Stack) -> Option<(U256, U256)> { + fn store_written(instruction: Instruction, stack: &dyn Stack) -> Option<(U256, U256)> { match instruction { instructions::SSTORE => Some((stack.peek(0).clone(), stack.peek(1).clone())), _ => None, @@ -604,7 +604,7 @@ impl Interpreter { fn exec_instruction( &mut self, gas: Cost, - ext: &mut vm::Ext, + ext: &mut dyn vm::Ext, instruction: Instruction, provided: Option, ) -> vm::Result> { @@ -1374,7 +1374,7 @@ impl Interpreter { Ok(InstructionResult::Ok) } - fn copy_data_to_memory(mem: &mut Vec, stack: &mut Stack, source: &[u8]) { + fn copy_data_to_memory(mem: &mut Vec, stack: &mut dyn Stack, source: &[u8]) { let dest_offset = stack.pop_back(); let source_offset = stack.pop_back(); let size = stack.pop_back(); @@ -1462,7 +1462,7 @@ mod tests { }; use vmtype::VMType; - fn interpreter(params: ActionParams, ext: &vm::Ext) -> Box { + fn interpreter(params: ActionParams, ext: &dyn vm::Ext) -> Box { Factory::new(VMType::Interpreter, 1).create(params, ext.schedule(), ext.depth()) } diff --git a/ethcore/light/src/cht.rs b/ethcore/light/src/cht.rs index 7b056b302..3d11c4aa2 100644 --- a/ethcore/light/src/cht.rs +++ b/ethcore/light/src/cht.rs @@ -82,7 +82,7 @@ impl> CHT { } let mut recorder = Recorder::with_depth(from_level); - let db: &HashDB<_, _> = &self.db; + let db: &dyn HashDB<_, _> = &self.db; let t = TrieDB::new(&db, &self.root)?; t.get_with(&key!(num), &mut recorder)?; diff --git a/ethcore/light/src/client/fetch.rs b/ethcore/light/src/client/fetch.rs index 0be6283dd..b9cb261c9 100644 --- a/ethcore/light/src/client/fetch.rs +++ b/ethcore/light/src/client/fetch.rs @@ -48,8 +48,8 @@ pub trait ChainDataFetcher: Send + Sync + 'static { fn epoch_transition( &self, _hash: H256, - _engine: Arc, - _checker: Arc>, + _engine: Arc, + _checker: Arc>, ) -> Self::Transition; } @@ -79,8 +79,8 @@ impl ChainDataFetcher for Unavailable { fn epoch_transition( &self, _hash: H256, - _engine: Arc, - _checker: Arc>, + _engine: Arc, + _checker: Arc>, ) -> Self::Transition { Err("fetching epoch transition proofs unavailable") } diff --git a/ethcore/light/src/client/header_chain.rs b/ethcore/light/src/client/header_chain.rs index 0946712cb..a9699aa74 100644 --- a/ethcore/light/src/client/header_chain.rs +++ b/ethcore/light/src/client/header_chain.rs @@ -202,7 +202,7 @@ pub struct HeaderChain { candidates: RwLock>, best_block: RwLock, live_epoch_proofs: RwLock>, - db: Arc, + db: Arc, col: Option, cache: Arc>, } @@ -210,7 +210,7 @@ pub struct HeaderChain { impl HeaderChain { /// Create a new header chain given this genesis block and database to read from. pub fn new( - db: Arc, + db: Arc, col: Option, spec: &Spec, cache: Arc>, @@ -955,7 +955,7 @@ mod tests { use parking_lot::Mutex; use std::time::Duration; - fn make_db() -> Arc { + fn make_db() -> Arc { Arc::new(kvdb_memorydb::create(0)) } diff --git a/ethcore/light/src/client/mod.rs b/ethcore/light/src/client/mod.rs index d4c3f3280..0cc898ac8 100644 --- a/ethcore/light/src/client/mod.rs +++ b/ethcore/light/src/client/mod.rs @@ -81,7 +81,7 @@ impl Default for Config { /// Trait for interacting with the header chain abstractly. pub trait LightChainClient: Send + Sync { /// Adds a new `LightChainNotify` listener. - fn add_listener(&self, listener: Weak); + fn add_listener(&self, listener: Weak); /// Get chain info. fn chain_info(&self) -> BlockChainInfo; @@ -103,7 +103,10 @@ pub trait LightChainClient: Send + Sync { fn score(&self, id: BlockId) -> Option; /// Get an iterator over a block and its ancestry. - fn ancestry_iter<'a>(&'a self, start: BlockId) -> Box + 'a>; + fn ancestry_iter<'a>( + &'a self, + start: BlockId, + ) -> Box + 'a>; /// Get the signing chain ID. fn signing_chain_id(&self) -> Option; @@ -113,7 +116,7 @@ pub trait LightChainClient: Send + Sync { fn env_info(&self, id: BlockId) -> Option; /// Get a handle to the consensus engine. - fn engine(&self) -> &Arc; + fn engine(&self) -> &Arc; /// Query whether a block is known. fn is_known(&self, hash: &H256) -> bool; @@ -163,23 +166,23 @@ impl AsLightClient for T { /// Light client implementation. pub struct Client { queue: HeaderQueue, - engine: Arc, + engine: Arc, chain: HeaderChain, report: RwLock, import_lock: Mutex<()>, - db: Arc, - listeners: RwLock>>, + db: Arc, + listeners: RwLock>>, fetcher: T, verify_full: bool, /// A closure to call when we want to restart the client - exit_handler: Mutex>>, + exit_handler: Mutex>>, } impl Client { /// Create a new `Client`. pub fn new( config: Config, - db: Arc, + db: Arc, chain_col: Option, spec: &Spec, fetcher: T, @@ -221,7 +224,7 @@ impl Client { } /// Adds a new `LightChainNotify` listener. - pub fn add_listener(&self, listener: Weak) { + pub fn add_listener(&self, listener: Weak) { self.listeners.write().push(listener); } @@ -398,7 +401,7 @@ impl Client { } /// Get a handle to the verification engine. - pub fn engine(&self) -> &Arc { + pub fn engine(&self) -> &Arc { &self.engine } @@ -439,7 +442,7 @@ impl Client { Arc::new(v) } - fn notify(&self, f: F) { + fn notify(&self, f: F) { for listener in &*self.listeners.read() { if let Some(listener) = listener.upgrade() { f(&*listener) @@ -567,7 +570,7 @@ impl Client { } impl LightChainClient for Client { - fn add_listener(&self, listener: Weak) { + fn add_listener(&self, listener: Weak) { Client::add_listener(self, listener) } @@ -595,7 +598,10 @@ impl LightChainClient for Client { Client::score(self, id) } - fn ancestry_iter<'a>(&'a self, start: BlockId) -> Box + 'a> { + fn ancestry_iter<'a>( + &'a self, + start: BlockId, + ) -> Box + 'a> { Box::new(Client::ancestry_iter(self, start)) } @@ -607,7 +613,7 @@ impl LightChainClient for Client { Client::env_info(self, id) } - fn engine(&self) -> &Arc { + fn engine(&self) -> &Arc { Client::engine(self) } @@ -668,7 +674,7 @@ impl ::ethcore::client::EngineClient for Client { }) } - fn as_full_client(&self) -> Option<&::ethcore::client::BlockChainClient> { + fn as_full_client(&self) -> Option<&dyn crate::ethcore::client::BlockChainClient> { None } diff --git a/ethcore/light/src/client/service.rs b/ethcore/light/src/client/service.rs index 3e03dde4b..94edd2dda 100644 --- a/ethcore/light/src/client/service.rs +++ b/ethcore/light/src/client/service.rs @@ -66,7 +66,7 @@ impl Service { config: ClientConfig, spec: &Spec, fetcher: T, - db: Arc, + db: Arc, cache: Arc>, ) -> Result { let io_service = IoService::::start().map_err(Error::Io)?; @@ -89,14 +89,14 @@ impl Service { } /// Set the actor to be notified on certain chain events - pub fn add_notify(&self, notify: Arc) { + pub fn add_notify(&self, notify: Arc) { self.client.add_listener(Arc::downgrade(¬ify)); } /// Register an I/O handler on the service. pub fn register_handler( &self, - handler: Arc + Send>, + handler: Arc + Send>, ) -> Result<(), IoError> { self.io_service.register_handler(handler) } diff --git a/ethcore/light/src/net/context.rs b/ethcore/light/src/net/context.rs index 5aa4b34a1..57a6c67b3 100644 --- a/ethcore/light/src/net/context.rs +++ b/ethcore/light/src/net/context.rs @@ -118,13 +118,13 @@ pub trait EventContext: BasicContext { fn peer(&self) -> PeerId; /// Treat the event context as a basic context. - fn as_basic(&self) -> &BasicContext; + fn as_basic(&self) -> &dyn BasicContext; } /// Basic context. pub struct TickCtx<'a> { /// Io context to enable dispatch. - pub io: &'a IoContext, + pub io: &'a dyn IoContext, /// Protocol implementation. pub proto: &'a LightProtocol, } @@ -155,7 +155,7 @@ impl<'a> BasicContext for TickCtx<'a> { /// an io context. pub struct Ctx<'a> { /// Io context to enable immediate response to events. - pub io: &'a IoContext, + pub io: &'a dyn IoContext, /// Protocol implementation. pub proto: &'a LightProtocol, /// Relevant peer for event. @@ -189,7 +189,7 @@ impl<'a> EventContext for Ctx<'a> { self.peer } - fn as_basic(&self) -> &BasicContext { + fn as_basic(&self) -> &dyn BasicContext { &*self } } diff --git a/ethcore/light/src/net/load_timer.rs b/ethcore/light/src/net/load_timer.rs index 1736fce0f..f8c638a37 100644 --- a/ethcore/light/src/net/load_timer.rs +++ b/ethcore/light/src/net/load_timer.rs @@ -89,7 +89,7 @@ pub struct LoadDistribution { impl LoadDistribution { /// Load rolling samples from the given store. - pub fn load(store: &SampleStore) -> Self { + pub fn load(store: &dyn SampleStore) -> Self { let mut samples = store.load(); for kind_samples in samples.values_mut() { @@ -146,7 +146,7 @@ impl LoadDistribution { } /// End the current time period. Provide a store to - pub fn end_period(&self, store: &SampleStore) { + pub fn end_period(&self, store: &dyn SampleStore) { let active_period = self.active_period.read(); let mut samples = self.samples.write(); diff --git a/ethcore/light/src/net/mod.rs b/ethcore/light/src/net/mod.rs index 632156418..fea8b8ae5 100644 --- a/ethcore/light/src/net/mod.rs +++ b/ethcore/light/src/net/mod.rs @@ -242,7 +242,7 @@ pub trait Handler: Send + Sync { /// Called when a peer connects. fn on_connect( &self, - _ctx: &EventContext, + _ctx: &dyn EventContext, _status: &Status, _capabilities: &Capabilities, ) -> PeerStatus { @@ -250,19 +250,25 @@ pub trait Handler: Send + Sync { } /// Called when a peer disconnects, with a list of unfulfilled request IDs as /// of yet. - fn on_disconnect(&self, _ctx: &EventContext, _unfulfilled: &[ReqId]) {} + fn on_disconnect(&self, _ctx: &dyn EventContext, _unfulfilled: &[ReqId]) {} /// Called when a peer makes an announcement. - fn on_announcement(&self, _ctx: &EventContext, _announcement: &Announcement) {} + fn on_announcement(&self, _ctx: &dyn EventContext, _announcement: &Announcement) {} /// Called when a peer requests relay of some transactions. - fn on_transactions(&self, _ctx: &EventContext, _relay: &[UnverifiedTransaction]) {} + fn on_transactions(&self, _ctx: &dyn EventContext, _relay: &[UnverifiedTransaction]) {} /// Called when a peer responds to requests. /// Responses not guaranteed to contain valid data and are not yet checked against /// the requests they correspond to. - fn on_responses(&self, _ctx: &EventContext, _req_id: ReqId, _responses: &[Response]) {} + fn on_responses(&self, _ctx: &dyn EventContext, _req_id: ReqId, _responses: &[Response]) {} /// Called when a peer responds with a transaction proof. Each proof is a vector of state items. - fn on_transaction_proof(&self, _ctx: &EventContext, _req_id: ReqId, _state_items: &[DBValue]) {} + fn on_transaction_proof( + &self, + _ctx: &dyn EventContext, + _req_id: ReqId, + _state_items: &[DBValue], + ) { + } /// Called to "tick" the handler periodically. - fn tick(&self, _ctx: &BasicContext) {} + fn tick(&self, _ctx: &dyn BasicContext) {} /// Called on abort. This signals to handlers that they should clean up /// and ignore peers. // TODO: coreresponding `on_activate`? @@ -298,7 +304,7 @@ pub struct Params { /// Initial capabilities. pub capabilities: Capabilities, /// The sample store (`None` if data shouldn't persist between runs). - pub sample_store: Option>, + pub sample_store: Option>, } /// Type alias for convenience. @@ -403,7 +409,7 @@ impl Statistics { // Locks must be acquired in the order declared, and when holding a read lock // on the peers, only one peer may be held at a time. pub struct LightProtocol { - provider: Arc, + provider: Arc, config: Config, genesis_hash: H256, network_id: u64, @@ -412,16 +418,16 @@ pub struct LightProtocol { capabilities: RwLock, flow_params: RwLock>, free_flow_params: Arc, - handlers: Vec>, + handlers: Vec>, req_id: AtomicUsize, - sample_store: Box, + sample_store: Box, load_distribution: LoadDistribution, statistics: RwLock, } impl LightProtocol { /// Create a new instance of the protocol manager. - pub fn new(provider: Arc, params: Params) -> Self { + pub fn new(provider: Arc, params: Params) -> Self { debug!(target: "pip", "Initializing light protocol handler"); let genesis_hash = provider.chain_info().genesis_hash; @@ -494,7 +500,7 @@ impl LightProtocol { /// with an event. pub fn request_from( &self, - io: &IoContext, + io: &dyn IoContext, peer_id: PeerId, requests: Requests, ) -> Result { @@ -543,7 +549,7 @@ impl LightProtocol { /// Make an announcement of new chain head and capabilities to all peers. /// The announcement is expected to be valid. - pub fn make_announcement(&self, io: &IoContext, mut announcement: Announcement) { + pub fn make_announcement(&self, io: &dyn IoContext, mut announcement: Announcement) { let mut reorgs_map = HashMap::new(); let now = Instant::now(); @@ -598,7 +604,7 @@ impl LightProtocol { /// These are intended to be added when the protocol structure /// is initialized as a means of customizing its behavior, /// and dispatching requests immediately upon events. - pub fn add_handler(&mut self, handler: Arc) { + pub fn add_handler(&mut self, handler: Arc) { self.handlers.push(handler); } @@ -667,7 +673,7 @@ impl LightProtocol { /// Handle a packet using the given io context. /// Packet data is _untrusted_, which means that invalid data won't lead to /// issues. - pub fn handle_packet(&self, io: &IoContext, peer: PeerId, packet_id: u8, data: &[u8]) { + pub fn handle_packet(&self, io: &dyn IoContext, peer: PeerId, packet_id: u8, data: &[u8]) { let rlp = Rlp::new(data); trace!(target: "pip", "Incoming packet {} from peer {}", packet_id, peer); @@ -694,7 +700,7 @@ impl LightProtocol { } // check timeouts and punish peers. - fn timeout_check(&self, io: &IoContext) { + fn timeout_check(&self, io: &dyn IoContext) { let now = Instant::now(); // handshake timeout @@ -735,7 +741,7 @@ impl LightProtocol { // propagate transactions to relay peers. // if we aren't on the mainnet, we just propagate to all relay peers - fn propagate_transactions(&self, io: &IoContext) { + fn propagate_transactions(&self, io: &dyn IoContext) { if self.capabilities.read().tx_relay { return; } @@ -785,7 +791,7 @@ impl LightProtocol { } /// called when a peer connects. - pub fn on_connect(&self, peer: PeerId, io: &IoContext) { + pub fn on_connect(&self, peer: PeerId, io: &dyn IoContext) { let proto_version = match io.protocol_version(peer).ok_or(Error::WrongNetwork) { Ok(pv) => pv, Err(e) => { @@ -837,7 +843,7 @@ impl LightProtocol { } /// called when a peer disconnects. - pub fn on_disconnect(&self, peer: PeerId, io: &IoContext) { + pub fn on_disconnect(&self, peer: PeerId, io: &dyn IoContext) { trace!(target: "pip", "Peer {} disconnecting", peer); self.pending_peers.write().remove(&peer); @@ -865,20 +871,20 @@ impl LightProtocol { } /// Execute the given closure with a basic context derived from the I/O context. - pub fn with_context(&self, io: &IoContext, f: F) -> T + pub fn with_context(&self, io: &dyn IoContext, f: F) -> T where - F: FnOnce(&BasicContext) -> T, + F: FnOnce(&dyn BasicContext) -> T, { f(&TickCtx { io, proto: self }) } - fn tick_handlers(&self, io: &IoContext) { + fn tick_handlers(&self, io: &dyn IoContext) { for handler in &self.handlers { handler.tick(&TickCtx { io, proto: self }) } } - fn begin_new_cost_period(&self, io: &IoContext) { + fn begin_new_cost_period(&self, io: &dyn IoContext) { self.load_distribution.end_period(&*self.sample_store); let avg_peer_count = self.statistics.read().avg_peer_count(); @@ -920,7 +926,7 @@ impl LightProtocol { impl LightProtocol { // Handle status message from peer. - fn status(&self, peer: PeerId, io: &IoContext, data: &Rlp) -> Result<(), Error> { + fn status(&self, peer: PeerId, io: &dyn IoContext, data: &Rlp) -> Result<(), Error> { let pending = match self.pending_peers.write().remove(&peer) { Some(pending) => pending, None => { @@ -992,7 +998,7 @@ impl LightProtocol { } // Handle an announcement. - fn announcement(&self, peer: PeerId, io: &IoContext, data: &Rlp) -> Result<(), Error> { + fn announcement(&self, peer: PeerId, io: &dyn IoContext, data: &Rlp) -> Result<(), Error> { if !self.peers.read().contains_key(&peer) { debug!(target: "pip", "Ignoring announcement from unknown peer"); return Ok(()); @@ -1040,7 +1046,7 @@ impl LightProtocol { } // Receive requests from a peer. - fn request(&self, peer_id: PeerId, io: &IoContext, raw: &Rlp) -> Result<(), Error> { + fn request(&self, peer_id: PeerId, io: &dyn IoContext, raw: &Rlp) -> Result<(), Error> { // the maximum amount of requests we'll fill in a single packet. const MAX_REQUESTS: usize = 256; @@ -1134,7 +1140,7 @@ impl LightProtocol { } // handle a packet with responses. - fn response(&self, peer: PeerId, io: &IoContext, raw: &Rlp) -> Result<(), Error> { + fn response(&self, peer: PeerId, io: &dyn IoContext, raw: &Rlp) -> Result<(), Error> { let (req_id, responses) = { let id_guard = self.pre_verify_response(peer, &raw)?; let responses: Vec = raw.list_at(2)?; @@ -1157,7 +1163,7 @@ impl LightProtocol { } // handle an update of request credits parameters. - fn update_credits(&self, peer_id: PeerId, io: &IoContext, raw: &Rlp) -> Result<(), Error> { + fn update_credits(&self, peer_id: PeerId, io: &dyn IoContext, raw: &Rlp) -> Result<(), Error> { let peers = self.peers.read(); let peer = peers.get(&peer_id).ok_or(Error::UnknownPeer)?; @@ -1196,7 +1202,7 @@ impl LightProtocol { fn acknowledge_update( &self, peer_id: PeerId, - _io: &IoContext, + _io: &dyn IoContext, _raw: &Rlp, ) -> Result<(), Error> { let peers = self.peers.read(); @@ -1218,7 +1224,12 @@ impl LightProtocol { } // Receive a set of transactions to relay. - fn relay_transactions(&self, peer: PeerId, io: &IoContext, data: &Rlp) -> Result<(), Error> { + fn relay_transactions( + &self, + peer: PeerId, + io: &dyn IoContext, + data: &Rlp, + ) -> Result<(), Error> { const MAX_TRANSACTIONS: usize = 256; let txs: Vec<_> = data @@ -1245,7 +1256,7 @@ impl LightProtocol { } // if something went wrong, figure out how much to punish the peer. -fn punish(peer: PeerId, io: &IoContext, e: &Error) { +fn punish(peer: PeerId, io: &dyn IoContext, e: &Error) { match e.punishment() { Punishment::None => {} Punishment::Disconnect => { @@ -1260,7 +1271,7 @@ fn punish(peer: PeerId, io: &IoContext, e: &Error) { } impl NetworkProtocolHandler for LightProtocol { - fn initialize(&self, io: &NetworkContext) { + fn initialize(&self, io: &dyn NetworkContext) { io.register_timer(TIMEOUT, TIMEOUT_INTERVAL) .expect("Error registering sync timer."); io.register_timer(TICK_TIMEOUT, TICK_TIMEOUT_INTERVAL) @@ -1273,19 +1284,19 @@ impl NetworkProtocolHandler for LightProtocol { .expect("Error registering statistics timer."); } - fn read(&self, io: &NetworkContext, peer: &PeerId, packet_id: u8, data: &[u8]) { + fn read(&self, io: &dyn NetworkContext, peer: &PeerId, packet_id: u8, data: &[u8]) { self.handle_packet(&io, *peer, packet_id, data); } - fn connected(&self, io: &NetworkContext, peer: &PeerId) { + fn connected(&self, io: &dyn NetworkContext, peer: &PeerId) { self.on_connect(*peer, &io); } - fn disconnected(&self, io: &NetworkContext, peer: &PeerId) { + fn disconnected(&self, io: &dyn NetworkContext, peer: &PeerId) { self.on_disconnect(*peer, &io); } - fn timeout(&self, io: &NetworkContext, timer: TimerToken) { + fn timeout(&self, io: &dyn NetworkContext, timer: TimerToken) { match timer { TIMEOUT => self.timeout_check(&io), TICK_TIMEOUT => self.tick_handlers(&io), diff --git a/ethcore/light/src/on_demand/mod.rs b/ethcore/light/src/on_demand/mod.rs index 981edadd5..82ed06ca5 100644 --- a/ethcore/light/src/on_demand/mod.rs +++ b/ethcore/light/src/on_demand/mod.rs @@ -99,7 +99,7 @@ pub trait OnDemandRequester: Send + Sync { /// Fails if back-reference are not coherent. fn request( &self, - ctx: &BasicContext, + ctx: &dyn BasicContext, requests: T, ) -> Result, basic_request::NoSuchOutput> where @@ -111,7 +111,7 @@ pub trait OnDemandRequester: Send + Sync { /// The returned vector of responses will correspond to the requests exactly. fn request_raw( &self, - ctx: &BasicContext, + ctx: &dyn BasicContext, requests: Vec, ) -> Result, basic_request::NoSuchOutput>; } @@ -396,7 +396,7 @@ pub struct OnDemand { impl OnDemandRequester for OnDemand { fn request_raw( &self, - ctx: &BasicContext, + ctx: &dyn BasicContext, requests: Vec, ) -> Result, basic_request::NoSuchOutput> { let (sender, receiver) = oneshot::channel(); @@ -460,7 +460,7 @@ impl OnDemandRequester for OnDemand { fn request( &self, - ctx: &BasicContext, + ctx: &dyn BasicContext, requests: T, ) -> Result, basic_request::NoSuchOutput> where @@ -543,7 +543,7 @@ impl OnDemand { // maybe dispatch pending requests. // sometimes - fn attempt_dispatch(&self, ctx: &BasicContext) { + fn attempt_dispatch(&self, ctx: &dyn BasicContext) { if !self.no_immediate_dispatch { self.dispatch_pending(ctx) } @@ -551,7 +551,7 @@ impl OnDemand { // dispatch pending requests, and discard those for which the corresponding // receiver has been dropped. - fn dispatch_pending(&self, ctx: &BasicContext) { + fn dispatch_pending(&self, ctx: &dyn BasicContext) { if self.pending.read().is_empty() { return; } @@ -606,7 +606,7 @@ impl OnDemand { // submit a pending request set. attempts to answer from cache before // going to the network. if complete, sends response and consumes the struct. - fn submit_pending(&self, ctx: &BasicContext, mut pending: Pending) { + fn submit_pending(&self, ctx: &dyn BasicContext, mut pending: Pending) { // answer as many requests from cache as we can, and schedule for dispatch // if incomplete. @@ -625,7 +625,7 @@ impl OnDemand { impl Handler for OnDemand { fn on_connect( &self, - ctx: &EventContext, + ctx: &dyn EventContext, status: &Status, capabilities: &Capabilities, ) -> PeerStatus { @@ -640,7 +640,7 @@ impl Handler for OnDemand { PeerStatus::Kept } - fn on_disconnect(&self, ctx: &EventContext, unfulfilled: &[ReqId]) { + fn on_disconnect(&self, ctx: &dyn EventContext, unfulfilled: &[ReqId]) { self.peers.write().remove(&ctx.peer()); let ctx = ctx.as_basic(); @@ -657,7 +657,7 @@ impl Handler for OnDemand { self.attempt_dispatch(ctx); } - fn on_announcement(&self, ctx: &EventContext, announcement: &Announcement) { + fn on_announcement(&self, ctx: &dyn EventContext, announcement: &Announcement) { { let mut peers = self.peers.write(); if let Some(ref mut peer) = peers.get_mut(&ctx.peer()) { @@ -671,7 +671,7 @@ impl Handler for OnDemand { fn on_responses( &self, - ctx: &EventContext, + ctx: &dyn EventContext, req_id: ReqId, responses: &[basic_request::Response], ) { @@ -713,7 +713,7 @@ impl Handler for OnDemand { self.submit_pending(ctx.as_basic(), pending); } - fn tick(&self, ctx: &BasicContext) { + fn tick(&self, ctx: &dyn BasicContext) { self.attempt_dispatch(ctx) } } diff --git a/ethcore/light/src/on_demand/request.rs b/ethcore/light/src/on_demand/request.rs index 7704903a2..5c74bfd7e 100644 --- a/ethcore/light/src/on_demand/request.rs +++ b/ethcore/light/src/on_demand/request.rs @@ -1117,7 +1117,7 @@ pub struct TransactionProof { // TODO: it's not really possible to provide this if the header is unknown. pub env_info: EnvInfo, /// Consensus engine. - pub engine: Arc, + pub engine: Arc, } impl TransactionProof { @@ -1164,9 +1164,9 @@ pub struct Signal { /// Block hash and number to fetch proof for. pub hash: H256, /// Consensus engine, used to check the proof. - pub engine: Arc, + pub engine: Arc, /// Special checker for the proof. - pub proof_check: Arc>, + pub proof_check: Arc>, } impl Signal { diff --git a/ethcore/light/src/on_demand/tests.rs b/ethcore/light/src/on_demand/tests.rs index 2085174a7..a173ee5de 100644 --- a/ethcore/light/src/on_demand/tests.rs +++ b/ethcore/light/src/on_demand/tests.rs @@ -51,7 +51,7 @@ impl EventContext for Context { } } - fn as_basic(&self) -> &BasicContext { + fn as_basic(&self) -> &dyn BasicContext { self } } diff --git a/ethcore/light/src/transaction_queue.rs b/ethcore/light/src/transaction_queue.rs index 980f71417..579169396 100644 --- a/ethcore/light/src/transaction_queue.rs +++ b/ethcore/light/src/transaction_queue.rs @@ -129,7 +129,7 @@ pub enum ImportDestination { Future, } -type Listener = Box; +type Listener = Box; /// Light transaction queue. See module docs for more details. #[derive(Default)] diff --git a/ethcore/node-filter/src/lib.rs b/ethcore/node-filter/src/lib.rs index 237ee7845..e3aa98e22 100644 --- a/ethcore/node-filter/src/lib.rs +++ b/ethcore/node-filter/src/lib.rs @@ -49,13 +49,13 @@ use_contract!(peer_set, "res/peer_set.json"); /// Connection filter that uses a contract to manage permissions. pub struct NodeFilter { - client: Weak, + client: Weak, contract_address: Address, } impl NodeFilter { /// Create a new instance. Accepts a contract address. - pub fn new(client: Weak, contract_address: Address) -> NodeFilter { + pub fn new(client: Weak, contract_address: Address) -> NodeFilter { NodeFilter { client, contract_address, @@ -127,7 +127,7 @@ mod test { ) .unwrap(); let filter = NodeFilter::new( - Arc::downgrade(&client) as Weak, + Arc::downgrade(&client) as Weak, contract_addr, ); let self1: NodeId = "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002".into(); diff --git a/ethcore/private-tx/src/encryptor.rs b/ethcore/private-tx/src/encryptor.rs index a95692747..107e5f897 100644 --- a/ethcore/private-tx/src/encryptor.rs +++ b/ethcore/private-tx/src/encryptor.rs @@ -77,7 +77,7 @@ pub struct SecretStoreEncryptor { config: EncryptorConfig, client: FetchClient, sessions: Mutex>, - signer: Arc, + signer: Arc, } impl SecretStoreEncryptor { @@ -85,7 +85,7 @@ impl SecretStoreEncryptor { pub fn new( config: EncryptorConfig, client: FetchClient, - signer: Arc, + signer: Arc, ) -> Result { Ok(SecretStoreEncryptor { config, diff --git a/ethcore/private-tx/src/error.rs b/ethcore/private-tx/src/error.rs index 347f0ced3..664003de7 100644 --- a/ethcore/private-tx/src/error.rs +++ b/ethcore/private-tx/src/error.rs @@ -116,7 +116,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::Io(e) => Some(e), Error::Decoder(e) => Some(e), diff --git a/ethcore/private-tx/src/lib.rs b/ethcore/private-tx/src/lib.rs index a48ae87de..44fdad512 100644 --- a/ethcore/private-tx/src/lib.rs +++ b/ethcore/private-tx/src/lib.rs @@ -198,17 +198,17 @@ impl Signer for KeyPairSigner { /// Manager of private transactions pub struct Provider { - encryptor: Box, + encryptor: Box, validator_accounts: HashSet
, signer_account: Option
, - notify: RwLock>>, + notify: RwLock>>, transactions_for_signing: RwLock, transactions_for_verification: VerificationStore, client: Arc, miner: Arc, - accounts: Arc, + accounts: Arc, channel: IoChannel, - keys_provider: Arc, + keys_provider: Arc, } #[derive(Debug)] @@ -228,11 +228,11 @@ impl Provider { pub fn new( client: Arc, miner: Arc, - accounts: Arc, - encryptor: Box, + accounts: Arc, + encryptor: Box, config: ProviderConfig, channel: IoChannel, - keys_provider: Arc, + keys_provider: Arc, ) -> Self { keys_provider.update_acl_contract(); Provider { @@ -253,13 +253,13 @@ impl Provider { // TODO [ToDr] Don't use `ChainNotify` here! // Better to create a separate notification type for this. /// Adds an actor to be notified on certain events - pub fn add_notify(&self, target: Arc) { + pub fn add_notify(&self, target: Arc) { self.notify.write().push(Arc::downgrade(&target)); } fn notify(&self, f: F) where - F: Fn(&ChainNotify), + F: Fn(&dyn ChainNotify), { for np in self.notify.read().iter() { if let Some(n) = np.upgrade() { diff --git a/ethcore/service/src/service.rs b/ethcore/service/src/service.rs index 69ec5b8d0..6efe3beaf 100644 --- a/ethcore/service/src/service.rs +++ b/ethcore/service/src/service.rs @@ -82,7 +82,7 @@ pub struct ClientService { client: Arc, snapshot: Arc, private_tx: Arc, - database: Arc, + database: Arc, _stop_guard: StopGuard, } @@ -91,13 +91,13 @@ impl ClientService { pub fn start( config: ClientConfig, spec: &Spec, - blockchain_db: Arc, + blockchain_db: Arc, snapshot_path: &Path, - restoration_db_handler: Box, + restoration_db_handler: Box, _ipc_path: &Path, miner: Arc, - signer: Arc, - encryptor: Box, + signer: Arc, + encryptor: Box, private_tx_conf: ethcore_private_tx::ProviderConfig, private_encryptor_conf: ethcore_private_tx::EncryptorConfig, ) -> Result { @@ -169,7 +169,7 @@ impl ClientService { /// Get general IO interface pub fn register_io_handler( &self, - handler: Arc + Send>, + handler: Arc + Send>, ) -> Result<(), IoError> { self.io_service.register_handler(handler) } @@ -195,12 +195,12 @@ impl ClientService { } /// Set the actor to be notified on certain chain events - pub fn add_notify(&self, notify: Arc) { + pub fn add_notify(&self, notify: Arc) { self.client.add_notify(notify); } /// Get a handle to the database. - pub fn db(&self) -> Arc { + pub fn db(&self) -> Arc { self.database.clone() } diff --git a/ethcore/src/account_db.rs b/ethcore/src/account_db.rs index ee90086fa..26b69ea25 100644 --- a/ethcore/src/account_db.rs +++ b/ethcore/src/account_db.rs @@ -61,9 +61,9 @@ impl Factory { /// This will panic when write operations are called. pub fn readonly<'db>( &self, - db: &'db HashDB, + db: &'db dyn HashDB, address_hash: H256, - ) -> Box + 'db> { + ) -> Box + 'db> { match *self { Factory::Mangled => Box::new(AccountDB::from_hash(db, address_hash)), Factory::Plain => Box::new(Wrapping(db)), @@ -73,9 +73,9 @@ impl Factory { /// Create a new mutable hashdb. pub fn create<'db>( &self, - db: &'db mut HashDB, + db: &'db mut dyn HashDB, address_hash: H256, - ) -> Box + 'db> { + ) -> Box + 'db> { match *self { Factory::Mangled => Box::new(AccountDBMut::from_hash(db, address_hash)), Factory::Plain => Box::new(WrappingMut(db)), @@ -87,19 +87,19 @@ impl Factory { /// DB backend wrapper for Account trie /// Transforms trie node keys for the database pub struct AccountDB<'db> { - db: &'db HashDB, + db: &'db dyn HashDB, address_hash: H256, } impl<'db> AccountDB<'db> { /// Create a new AccountDB from an address. #[cfg(test)] - pub fn new(db: &'db HashDB, address: &Address) -> Self { + pub fn new(db: &'db dyn HashDB, address: &Address) -> Self { Self::from_hash(db, keccak(address)) } /// Create a new AcountDB from an address' hash. - pub fn from_hash(db: &'db HashDB, address_hash: H256) -> Self { + pub fn from_hash(db: &'db dyn HashDB, address_hash: H256) -> Self { AccountDB { db: db, address_hash: address_hash, @@ -108,10 +108,10 @@ impl<'db> AccountDB<'db> { } impl<'db> AsHashDB for AccountDB<'db> { - fn as_hash_db(&self) -> &HashDB { + fn as_hash_db(&self) -> &dyn HashDB { self } - fn as_hash_db_mut(&mut self) -> &mut HashDB { + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self } } @@ -146,19 +146,19 @@ impl<'db> HashDB for AccountDB<'db> { /// DB backend wrapper for Account trie pub struct AccountDBMut<'db> { - db: &'db mut HashDB, + db: &'db mut dyn HashDB, address_hash: H256, } impl<'db> AccountDBMut<'db> { /// Create a new AccountDB from an address. #[cfg(test)] - pub fn new(db: &'db mut HashDB, address: &Address) -> Self { + pub fn new(db: &'db mut dyn HashDB, address: &Address) -> Self { Self::from_hash(db, keccak(address)) } /// Create a new AcountDB from an address' hash. - pub fn from_hash(db: &'db mut HashDB, address_hash: H256) -> Self { + pub fn from_hash(db: &'db mut dyn HashDB, address_hash: H256) -> Self { AccountDBMut { db: db, address_hash: address_hash, @@ -217,21 +217,21 @@ impl<'db> HashDB for AccountDBMut<'db> { } impl<'db> AsHashDB for AccountDBMut<'db> { - fn as_hash_db(&self) -> &HashDB { + fn as_hash_db(&self) -> &dyn HashDB { self } - fn as_hash_db_mut(&mut self) -> &mut HashDB { + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self } } -struct Wrapping<'db>(&'db HashDB); +struct Wrapping<'db>(&'db dyn HashDB); impl<'db> AsHashDB for Wrapping<'db> { - fn as_hash_db(&self) -> &HashDB { + fn as_hash_db(&self) -> &dyn HashDB { self } - fn as_hash_db_mut(&mut self) -> &mut HashDB { + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self } } @@ -264,12 +264,12 @@ impl<'db> HashDB for Wrapping<'db> { } } -struct WrappingMut<'db>(&'db mut HashDB); +struct WrappingMut<'db>(&'db mut dyn HashDB); impl<'db> AsHashDB for WrappingMut<'db> { - fn as_hash_db(&self) -> &HashDB { + fn as_hash_db(&self) -> &dyn HashDB { self } - fn as_hash_db_mut(&mut self) -> &mut HashDB { + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self } } diff --git a/ethcore/src/block.rs b/ethcore/src/block.rs index c7036bded..3e45af440 100644 --- a/ethcore/src/block.rs +++ b/ethcore/src/block.rs @@ -61,7 +61,7 @@ use types::{ /// maintain the system `state()`. We also archive execution receipts in preparation for later block creation. pub struct OpenBlock<'x> { block: ExecutedBlock, - engine: &'x EthEngine, + engine: &'x dyn EthEngine, } /// Just like `OpenBlock`, except that we've applied `Engine::on_close_block`, finished up the non-seal header fields, @@ -163,7 +163,7 @@ pub trait Drain { impl<'x> OpenBlock<'x> { /// Create a new `OpenBlock` ready for transaction pushing. pub fn new<'a, I: IntoIterator>( - engine: &'x EthEngine, + engine: &'x dyn EthEngine, factories: Factories, tracing: bool, db: StateDB, @@ -421,7 +421,7 @@ impl ClosedBlock { } /// Given an engine reference, reopen the `ClosedBlock` into an `OpenBlock`. - pub fn reopen(self, engine: &EthEngine) -> OpenBlock { + pub fn reopen(self, engine: &dyn EthEngine) -> OpenBlock { // revert rewards (i.e. set state back at last transaction's state). let mut block = self.block; block.state = self.unclosed_state; @@ -451,7 +451,7 @@ impl LockedBlock { /// Provide a valid seal in order to turn this into a `SealedBlock`. /// /// NOTE: This does not check the validity of `seal` with the engine. - pub fn seal(self, engine: &EthEngine, seal: Vec) -> Result { + pub fn seal(self, engine: &dyn EthEngine, seal: Vec) -> Result { let expected_seal_fields = engine.seal_fields(&self.header); let mut s = self; if seal.len() != expected_seal_fields { @@ -472,7 +472,7 @@ impl LockedBlock { /// This does check the validity of `seal` with the engine. /// Returns the `ClosedBlock` back again if the seal is no good. /// TODO(https://github.com/paritytech/parity-ethereum/issues/10407): This is currently only used in POW chain call paths, we should really merge it with seal() above. - pub fn try_seal(self, engine: &EthEngine, seal: Vec) -> Result { + pub fn try_seal(self, engine: &dyn EthEngine, seal: Vec) -> Result { let mut s = self; s.block.header.set_seal(seal); s.block.header.compute_hash(); @@ -511,14 +511,14 @@ pub(crate) fn enact( header: Header, transactions: Vec, uncles: Vec
, - engine: &EthEngine, + engine: &dyn EthEngine, tracing: bool, db: StateDB, parent: &Header, last_hashes: Arc, factories: Factories, is_epoch_begin: bool, - ancestry: &mut Iterator, + ancestry: &mut dyn Iterator, ) -> Result { // For trace log let trace_state = if log_enabled!(target: "enact", ::log::Level::Trace) { @@ -569,14 +569,14 @@ pub(crate) fn enact( /// Enact the block given by `block_bytes` using `engine` on the database `db` with given `parent` block header pub fn enact_verified( block: PreverifiedBlock, - engine: &EthEngine, + engine: &dyn EthEngine, tracing: bool, db: StateDB, parent: &Header, last_hashes: Arc, factories: Factories, is_epoch_begin: bool, - ancestry: &mut Iterator, + ancestry: &mut dyn Iterator, ) -> Result { enact( block.header, @@ -610,7 +610,7 @@ mod tests { /// Enact the block given by `block_bytes` using `engine` on the database `db` with given `parent` block header fn enact_bytes( block_bytes: Vec, - engine: &EthEngine, + engine: &dyn EthEngine, tracing: bool, db: StateDB, parent: &Header, @@ -667,7 +667,7 @@ mod tests { /// Enact the block given by `block_bytes` using `engine` on the database `db` with given `parent` block header. Seal the block aferwards fn enact_and_seal( block_bytes: Vec, - engine: &EthEngine, + engine: &dyn EthEngine, tracing: bool, db: StateDB, parent: &Header, diff --git a/ethcore/src/client/ancient_import.rs b/ethcore/src/client/ancient_import.rs index de5f4b8ee..5eafafddd 100644 --- a/ethcore/src/client/ancient_import.rs +++ b/ethcore/src/client/ancient_import.rs @@ -32,13 +32,13 @@ const HEAVY_VERIFY_RATE: f32 = 0.02; /// Ancient block verifier: import an ancient sequence of blocks in order from a starting /// epoch. pub struct AncientVerifier { - cur_verifier: RwLock>>>, - engine: Arc, + cur_verifier: RwLock>>>, + engine: Arc, } impl AncientVerifier { /// Create a new ancient block verifier with the given engine. - pub fn new(engine: Arc) -> Self { + pub fn new(engine: Arc) -> Self { AncientVerifier { cur_verifier: RwLock::new(None), engine, @@ -93,7 +93,7 @@ impl AncientVerifier { &self, header: &Header, chain: &BlockChain, - ) -> Result>, ::error::Error> { + ) -> Result>, ::error::Error> { trace!(target: "client", "Initializing ancient block restoration."); let current_epoch_data = chain .epoch_transitions() diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index 848960c3b..0fc8f0ecc 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -184,7 +184,7 @@ struct Importer { pub ancient_verifier: AncientVerifier, /// Ethereum engine to be used during import - pub engine: Arc, + pub engine: Arc, /// A lru cache of recently detected bad blocks pub bad_blocks: bad_blocks::BadBlocks, @@ -206,7 +206,7 @@ pub struct Client { chain: RwLock>, tracedb: RwLock>, - engine: Arc, + engine: Arc, /// Client configuration config: ClientConfig, @@ -261,7 +261,7 @@ pub struct Client { impl Importer { pub fn new( config: &ClientConfig, - engine: Arc, + engine: Arc, message_channel: IoChannel, miner: Arc, ) -> Result { @@ -517,7 +517,7 @@ impl Importer { &self, unverified: Unverified, receipts_bytes: &[u8], - db: &KeyValueDB, + db: &dyn KeyValueDB, chain: &BlockChain, ) -> EthcoreResult<()> { let receipts = ::rlp::decode_list(receipts_bytes); @@ -833,7 +833,7 @@ impl Client { pub fn new( config: ClientConfig, spec: &Spec, - db: Arc, + db: Arc, miner: Arc, message_channel: IoChannel, ) -> Result, ::error::Error> { @@ -999,7 +999,7 @@ impl Client { } /// Adds an actor to be notified on certain events - pub fn add_notify(&self, target: Arc) { + pub fn add_notify(&self, target: Arc) { self.notify.write().push(Arc::downgrade(&target)); } @@ -1015,13 +1015,13 @@ impl Client { } /// Returns engine reference. - pub fn engine(&self) -> &EthEngine { + pub fn engine(&self) -> &dyn EthEngine { &*self.engine } fn notify(&self, f: F) where - F: Fn(&ChainNotify), + F: Fn(&dyn ChainNotify), { for np in &*self.notify.read() { if let Some(n) = np.upgrade() { @@ -1936,7 +1936,7 @@ impl Call for Client { } impl EngineInfo for Client { - fn engine(&self) -> &EthEngine { + fn engine(&self) -> &dyn EthEngine { Client::engine(self) } } @@ -1967,7 +1967,7 @@ impl BlockChainClient for Client { &self, block: BlockId, analytics: CallAnalytics, - ) -> Result>, CallError> { + ) -> Result>, CallError> { let mut env_info = self.env_info(block).ok_or(CallError::StatePruned)?; let body = self.block_body(block).ok_or(CallError::StatePruned)?; let mut state = self @@ -2895,7 +2895,7 @@ impl super::traits::EngineClient for Client { self.chain.read().epoch_transition_for(parent_hash) } - fn as_full_client(&self) -> Option<&BlockChainClient> { + fn as_full_client(&self) -> Option<&dyn BlockChainClient> { Some(self) } diff --git a/ethcore/src/client/io_message.rs b/ethcore/src/client/io_message.rs index 7d57f694c..2ae1db3e2 100644 --- a/ethcore/src/client/io_message.rs +++ b/ethcore/src/client/io_message.rs @@ -47,7 +47,7 @@ impl ClientIoMessage { } /// A function to invoke in the client thread. -pub struct Callback(pub Box); +pub struct Callback(pub Box); impl fmt::Debug for Callback { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { diff --git a/ethcore/src/client/test_client.rs b/ethcore/src/client/test_client.rs index 6221a3f53..b6bcbeb0b 100644 --- a/ethcore/src/client/test_client.rs +++ b/ethcore/src/client/test_client.rs @@ -715,7 +715,7 @@ impl StateClient for TestBlockChainClient { } impl EngineInfo for TestBlockChainClient { - fn engine(&self) -> &EthEngine { + fn engine(&self) -> &dyn EthEngine { unimplemented!() } } @@ -743,7 +743,7 @@ impl BlockChainClient for TestBlockChainClient { &self, _block: BlockId, _analytics: CallAnalytics, - ) -> Result>, CallError> { + ) -> Result>, CallError> { Ok(Box::new( self.traces .read() @@ -1110,7 +1110,7 @@ impl super::traits::EngineClient for TestBlockChainClient { None } - fn as_full_client(&self) -> Option<&BlockChainClient> { + fn as_full_client(&self) -> Option<&dyn BlockChainClient> { Some(self) } diff --git a/ethcore/src/client/trace.rs b/ethcore/src/client/trace.rs index 25d34b733..a9a5c8590 100644 --- a/ethcore/src/client/trace.rs +++ b/ethcore/src/client/trace.rs @@ -23,11 +23,11 @@ use types::BlockNumber; impl TraceDatabaseExtras for BlockChain { fn block_hash(&self, block_number: BlockNumber) -> Option { - (self as &BlockProvider).block_hash(block_number) + (self as &dyn BlockProvider).block_hash(block_number) } fn transaction_hash(&self, block_number: BlockNumber, tx_position: usize) -> Option { - (self as &BlockProvider) + (self as &dyn BlockProvider) .block_hash(block_number) .and_then(|block_hash| { let tx_address = TransactionAddress { diff --git a/ethcore/src/client/traits.rs b/ethcore/src/client/traits.rs index 72050737d..77577dbce 100644 --- a/ethcore/src/client/traits.rs +++ b/ethcore/src/client/traits.rs @@ -56,7 +56,7 @@ use verification::queue::{kind::blocks::Unverified, QueueInfo as BlockQueueInfo} /// State information to be used during client query pub enum StateOrBlock { /// State to be used, may be pending - State(Box), + State(Box), /// Id of an existing block from a chain to get state from Block(BlockId), @@ -68,8 +68,8 @@ impl From for StateOrBlock { } } -impl From> for StateOrBlock { - fn from(info: Box) -> StateOrBlock { +impl From> for StateOrBlock { + fn from(info: Box) -> StateOrBlock { StateOrBlock::State(info) } } @@ -203,7 +203,7 @@ pub trait Call { /// Provides `engine` method pub trait EngineInfo { /// Get underlying engine object - fn engine(&self) -> &EthEngine; + fn engine(&self) -> &dyn EthEngine; } /// IO operations that should off-load heavy work to another thread. @@ -353,7 +353,7 @@ pub trait BlockChainClient: &self, block: BlockId, analytics: CallAnalytics, - ) -> Result>, CallError>; + ) -> Result>, CallError>; /// Returns traces matching given filter. fn filter_traces(&self, filter: TraceFilter) -> Option>; @@ -501,7 +501,7 @@ pub trait EngineClient: Sync + Send + ChainInfo { fn epoch_transition_for(&self, parent_hash: H256) -> Option<::engines::EpochTransition>; /// Attempt to cast the engine client to a full client. - fn as_full_client(&self) -> Option<&BlockChainClient>; + fn as_full_client(&self) -> Option<&dyn BlockChainClient>; /// Get a block number by ID. fn block_number(&self, id: BlockId) -> Option; diff --git a/ethcore/src/engines/authority_round/mod.rs b/ethcore/src/engines/authority_round/mod.rs index dfdf2e48b..485a7ea04 100644 --- a/ethcore/src/engines/authority_round/mod.rs +++ b/ethcore/src/engines/authority_round/mod.rs @@ -72,7 +72,7 @@ pub struct AuthorityRoundParams { /// Starting step, pub start_step: Option, /// Valid validators. - pub validators: Box, + pub validators: Box, /// Chain score validation transition block. pub validate_score_transition: u64, /// Monotonic step validation transition block. @@ -240,9 +240,9 @@ impl EpochManager { // zoom to epoch for given header. returns true if succeeded, false otherwise. fn zoom_to( &mut self, - client: &EngineClient, + client: &dyn EngineClient, machine: &EthereumMachine, - validators: &ValidatorSet, + validators: &dyn ValidatorSet, header: &Header, ) -> bool { let last_was_parent = self.finality_checker.subchain_head() == Some(*header.parent_hash()); @@ -348,7 +348,7 @@ impl EmptyStep { } } - fn verify(&self, validators: &ValidatorSet) -> Result { + fn verify(&self, validators: &dyn ValidatorSet) -> Result { let message = keccak(empty_step_rlp(self.step, &self.parent_hash)); let correct_proposer = step_proposer(validators, &self.parent_hash, self.step); @@ -449,9 +449,9 @@ struct PermissionedStep { pub struct AuthorityRound { transition_service: IoService<()>, step: Arc, - client: Arc>>>, - signer: RwLock>>, - validators: Box, + client: Arc>>>, + signer: RwLock>>, + validators: Box, validate_score_transition: u64, validate_step_transition: u64, empty_steps: Mutex>, @@ -631,13 +631,18 @@ fn header_empty_steps_signers( } } -fn step_proposer(validators: &ValidatorSet, bh: &H256, step: u64) -> Address { +fn step_proposer(validators: &dyn ValidatorSet, bh: &H256, step: u64) -> Address { let proposer = validators.get(bh, step as usize); trace!(target: "engine", "Fetched proposer for step {}: {}", step, proposer); proposer } -fn is_step_proposer(validators: &ValidatorSet, bh: &H256, step: u64, address: &Address) -> bool { +fn is_step_proposer( + validators: &dyn ValidatorSet, + bh: &H256, + step: u64, + address: &Address, +) -> bool { step_proposer(validators, bh, step) == *address } @@ -671,7 +676,7 @@ fn verify_timestamp(step: &Step, header_step: u64) -> Result<(), BlockError> { fn verify_external( header: &Header, - validators: &ValidatorSet, + validators: &dyn ValidatorSet, empty_steps_transition: u64, ) -> Result<(), Error> { let header_step = header_step(header, empty_steps_transition)?; @@ -805,7 +810,7 @@ impl AuthorityRound { fn epoch_set<'a>( &'a self, header: &Header, - ) -> Result<(CowLike, BlockNumber), Error> { + ) -> Result<(CowLike, BlockNumber), Error> { Ok(if self.immediate_transitions { (CowLike::Borrowed(&*self.validators), header.number()) } else { @@ -903,7 +908,7 @@ impl AuthorityRound { header: &Header, current_step: u64, parent_step: u64, - validators: &ValidatorSet, + validators: &dyn ValidatorSet, set_number: u64, ) { // we're building on top of the genesis block so don't report any skipped steps @@ -937,7 +942,7 @@ impl AuthorityRound { fn build_finality( &self, chain_head: &Header, - ancestry: &mut Iterator, + ancestry: &mut dyn Iterator, ) -> Vec { if self.immediate_transitions { return Vec::new(); @@ -1019,7 +1024,7 @@ fn unix_now() -> Duration { struct TransitionHandler { step: Arc, - client: Arc>>>, + client: Arc>>>, } const ENGINE_TIMEOUT_TOKEN: TimerToken = 23; @@ -1306,7 +1311,7 @@ impl Engine for AuthorityRound { &self, block: &mut ExecutedBlock, epoch_begin: bool, - _ancestry: &mut Iterator, + _ancestry: &mut dyn Iterator, ) -> Result<(), Error> { // with immediate transitions, we don't use the epoch mechanism anyway. // the genesis is always considered an epoch, but we ignore it intentionally. @@ -1728,12 +1733,12 @@ impl Engine for AuthorityRound { } } - fn register_client(&self, client: Weak) { + fn register_client(&self, client: Weak) { *self.client.write() = Some(client.clone()); self.validators.register_client(client); } - fn set_signer(&self, signer: Box) { + fn set_signer(&self, signer: Box) { *self.signer.write() = Some(signer); } @@ -1746,7 +1751,7 @@ impl Engine for AuthorityRound { .sign(hash)?) } - fn snapshot_components(&self) -> Option> { + fn snapshot_components(&self) -> Option> { if self.immediate_transitions { None } else { @@ -1761,7 +1766,7 @@ impl Engine for AuthorityRound { fn ancestry_actions( &self, header: &Header, - ancestry: &mut Iterator, + ancestry: &mut dyn Iterator, ) -> Vec { let finalized = self.build_finality( header, @@ -2171,7 +2176,7 @@ mod tests { (spec, tap, accounts) } - fn empty_step(engine: &EthEngine, step: u64, parent_hash: &H256) -> EmptyStep { + fn empty_step(engine: &dyn EthEngine, step: u64, parent_hash: &H256) -> EmptyStep { let empty_step_rlp = super::empty_step_rlp(step, parent_hash); let signature = engine.sign(keccak(&empty_step_rlp)).unwrap().into(); let parent_hash = parent_hash.clone(); @@ -2182,7 +2187,7 @@ mod tests { } } - fn sealed_empty_step(engine: &EthEngine, step: u64, parent_hash: &H256) -> SealedEmptyStep { + fn sealed_empty_step(engine: &dyn EthEngine, step: u64, parent_hash: &H256) -> SealedEmptyStep { let empty_step_rlp = super::empty_step_rlp(step, parent_hash); let signature = engine.sign(keccak(&empty_step_rlp)).unwrap().into(); SealedEmptyStep { signature, step } diff --git a/ethcore/src/engines/basic_authority.rs b/ethcore/src/engines/basic_authority.rs index e54affdf7..648693bb0 100644 --- a/ethcore/src/engines/basic_authority.rs +++ b/ethcore/src/engines/basic_authority.rs @@ -54,7 +54,7 @@ impl super::EpochVerifier for EpochVerifier { } } -fn verify_external(header: &Header, validators: &ValidatorSet) -> Result<(), Error> { +fn verify_external(header: &Header, validators: &dyn ValidatorSet) -> Result<(), Error> { use rlp::Rlp; // Check if the signature belongs to a validator, can depend on parent state. @@ -74,8 +74,8 @@ fn verify_external(header: &Header, validators: &ValidatorSet) -> Result<(), Err /// Engine using `BasicAuthority`, trivial proof-of-authority consensus. pub struct BasicAuthority { machine: EthereumMachine, - signer: RwLock>>, - validators: Box, + signer: RwLock>>, + validators: Box, } impl BasicAuthority { @@ -201,11 +201,11 @@ impl Engine for BasicAuthority { } } - fn register_client(&self, client: Weak) { + fn register_client(&self, client: Weak) { self.validators.register_client(client); } - fn set_signer(&self, signer: Box) { + fn set_signer(&self, signer: Box) { *self.signer.write() = Some(signer); } @@ -218,7 +218,7 @@ impl Engine for BasicAuthority { .sign(hash)?) } - fn snapshot_components(&self) -> Option> { + fn snapshot_components(&self) -> Option> { None } diff --git a/ethcore/src/engines/clique/mod.rs b/ethcore/src/engines/clique/mod.rs index a7bbdd424..7d1845e6d 100644 --- a/ethcore/src/engines/clique/mod.rs +++ b/ethcore/src/engines/clique/mod.rs @@ -163,10 +163,10 @@ pub struct Clique { epoch_length: u64, period: u64, machine: EthereumMachine, - client: RwLock>>, + client: RwLock>>, block_state_by_hash: RwLock>, proposals: RwLock>, - signer: RwLock>>, + signer: RwLock>>, } #[cfg(test)] @@ -175,10 +175,10 @@ pub struct Clique { pub epoch_length: u64, pub period: u64, pub machine: EthereumMachine, - pub client: RwLock>>, + pub client: RwLock>>, pub block_state_by_hash: RwLock>, pub proposals: RwLock>, - pub signer: RwLock>>, + pub signer: RwLock>>, } impl Clique { @@ -383,7 +383,7 @@ impl Engine for Clique { &self, _block: &mut ExecutedBlock, _epoch_begin: bool, - _ancestry: &mut Iterator, + _ancestry: &mut dyn Iterator, ) -> Result<(), Error> { Ok(()) } @@ -767,12 +767,12 @@ impl Engine for Clique { } } - fn set_signer(&self, signer: Box) { + fn set_signer(&self, signer: Box) { trace!(target: "engine", "set_signer: {}", signer.address()); *self.signer.write() = Some(signer); } - fn register_client(&self, client: Weak) { + fn register_client(&self, client: Weak) { *self.client.write() = Some(client.clone()); } diff --git a/ethcore/src/engines/mod.rs b/ethcore/src/engines/mod.rs index cb4942216..e2e91f25b 100644 --- a/ethcore/src/engines/mod.rs +++ b/ethcore/src/engines/mod.rs @@ -181,11 +181,11 @@ pub enum Seal { } /// A system-calling closure. Enacts calls on a block's state from the system address. -pub type SystemCall<'a> = FnMut(Address, Vec) -> Result, String> + 'a; +pub type SystemCall<'a> = dyn FnMut(Address, Vec) -> Result, String> + 'a; /// A system-calling closure. Enacts calls on a block's state with code either from an on-chain contract, or hard-coded EVM or WASM (if enabled on-chain) codes. pub type SystemOrCodeCall<'a> = - FnMut(SystemOrCodeCallKind, Vec) -> Result, String> + 'a; + dyn FnMut(SystemOrCodeCallKind, Vec) -> Result, String> + 'a; /// Kind of SystemOrCodeCall, this is either an on-chain address, or code. #[derive(PartialEq, Debug, Clone)] @@ -223,10 +223,10 @@ pub fn default_system_or_code_call<'a>( } /// Type alias for a function we can get headers by hash through. -pub type Headers<'a, H> = Fn(H256) -> Option + 'a; +pub type Headers<'a, H> = dyn Fn(H256) -> Option + 'a; /// Type alias for a function we can query pending transitions by block hash through. -pub type PendingTransitionStore<'a> = Fn(H256) -> Option + 'a; +pub type PendingTransitionStore<'a> = dyn Fn(H256) -> Option + 'a; /// Proof dependent on state. pub trait StateDependentProof: Send + Sync { @@ -243,16 +243,16 @@ pub enum Proof { /// Known proof (extracted from signal) Known(Vec), /// State dependent proof. - WithState(Arc>), + WithState(Arc>), } /// Generated epoch verifier. pub enum ConstructedVerifier<'a, M: Machine> { /// Fully trusted verifier. - Trusted(Box>), + Trusted(Box>), /// Verifier unconfirmed. Check whether given finality proof finalizes given hash /// under previous epoch. - Unconfirmed(Box>, &'a [u8], H256), + Unconfirmed(Box>, &'a [u8], H256), /// Error constructing verifier. Err(Error), } @@ -260,7 +260,7 @@ pub enum ConstructedVerifier<'a, M: Machine> { impl<'a, M: Machine> ConstructedVerifier<'a, M> { /// Convert to a result, indicating that any necessary confirmation has been done /// already. - pub fn known_confirmed(self) -> Result>, Error> { + pub fn known_confirmed(self) -> Result>, Error> { match self { ConstructedVerifier::Trusted(v) | ConstructedVerifier::Unconfirmed(v, _, _) => Ok(v), ConstructedVerifier::Err(e) => Err(e), @@ -314,7 +314,7 @@ pub trait Engine: Sync + Send { &self, _block: &mut ExecutedBlock, _epoch_begin: bool, - _ancestry: &mut Iterator, + _ancestry: &mut dyn Iterator, ) -> Result<(), M::Error> { Ok(()) } @@ -467,7 +467,7 @@ pub trait Engine: Sync + Send { } /// Register a component which signs consensus messages. - fn set_signer(&self, _signer: Box) {} + fn set_signer(&self, _signer: Box) {} /// Sign using the EngineSigner, to be used for consensus tx signing. fn sign(&self, _hash: H256) -> Result { @@ -482,7 +482,7 @@ pub trait Engine: Sync + Send { /// Create a factory for building snapshot chunks and restoring from them. /// Returning `None` indicates that this engine doesn't support snapshot creation. - fn snapshot_components(&self) -> Option> { + fn snapshot_components(&self) -> Option> { None } @@ -511,7 +511,7 @@ pub trait Engine: Sync + Send { fn ancestry_actions( &self, _header: &Header, - _ancestry: &mut Iterator, + _ancestry: &mut dyn Iterator, ) -> Vec { Vec::new() } diff --git a/ethcore/src/engines/null_engine.rs b/ethcore/src/engines/null_engine.rs index eac037ce9..16cc2ee9b 100644 --- a/ethcore/src/engines/null_engine.rs +++ b/ethcore/src/engines/null_engine.rs @@ -117,7 +117,7 @@ impl Engine for NullEngine { Ok(()) } - fn snapshot_components(&self) -> Option> { + fn snapshot_components(&self) -> Option> { Some(Box::new(::snapshot::PowSnapshot::new(10000, 10000))) } diff --git a/ethcore/src/engines/signer.rs b/ethcore/src/engines/signer.rs index fa238dc5a..9c62f48cb 100644 --- a/ethcore/src/engines/signer.rs +++ b/ethcore/src/engines/signer.rs @@ -29,7 +29,7 @@ pub trait EngineSigner: Send + Sync { } /// Creates a new `EngineSigner` from given key pair. -pub fn from_keypair(keypair: ethkey::KeyPair) -> Box { +pub fn from_keypair(keypair: ethkey::KeyPair) -> Box { Box::new(Signer(keypair)) } diff --git a/ethcore/src/engines/validator_set/contract.rs b/ethcore/src/engines/validator_set/contract.rs index 776858a3c..4a6b1d948 100644 --- a/ethcore/src/engines/validator_set/contract.rs +++ b/ethcore/src/engines/validator_set/contract.rs @@ -34,7 +34,7 @@ use_contract!(validator_report, "res/contracts/validator_report.json"); pub struct ValidatorContract { contract_address: Address, validators: ValidatorSafeContract, - client: RwLock>>, // TODO [keorn]: remove + client: RwLock>>, // TODO [keorn]: remove } impl ValidatorContract { @@ -143,7 +143,7 @@ impl ValidatorSet for ValidatorContract { } } - fn register_client(&self, client: Weak) { + fn register_client(&self, client: Weak) { self.validators.register_client(client.clone()); *self.client.write() = Some(client); } diff --git a/ethcore/src/engines/validator_set/mod.rs b/ethcore/src/engines/validator_set/mod.rs index ca3768960..bad86c414 100644 --- a/ethcore/src/engines/validator_set/mod.rs +++ b/ethcore/src/engines/validator_set/mod.rs @@ -40,7 +40,7 @@ use self::{contract::ValidatorContract, multi::Multi, safe_contract::ValidatorSa use super::SystemCall; /// Creates a validator set from spec. -pub fn new_validator_set(spec: ValidatorSpec) -> Box { +pub fn new_validator_set(spec: ValidatorSpec) -> Box { match spec { ValidatorSpec::List(list) => { Box::new(SimpleList::new(list.into_iter().map(Into::into).collect())) @@ -168,5 +168,5 @@ pub trait ValidatorSet: Send + Sync + 'static { /// Notifies about benign misbehaviour. fn report_benign(&self, _validator: &Address, _set_block: BlockNumber, _block: BlockNumber) {} /// Allows blockchain state access. - fn register_client(&self, _client: Weak) {} + fn register_client(&self, _client: Weak) {} } diff --git a/ethcore/src/engines/validator_set/multi.rs b/ethcore/src/engines/validator_set/multi.rs index 4a1f45b56..912ab622b 100644 --- a/ethcore/src/engines/validator_set/multi.rs +++ b/ethcore/src/engines/validator_set/multi.rs @@ -27,15 +27,16 @@ use super::{SystemCall, ValidatorSet}; use client::EngineClient; use machine::{AuxiliaryData, Call, EthereumMachine}; -type BlockNumberLookup = Box Result + Send + Sync + 'static>; +type BlockNumberLookup = + Box Result + Send + Sync + 'static>; pub struct Multi { - sets: BTreeMap>, + sets: BTreeMap>, block_number: RwLock, } impl Multi { - pub fn new(set_map: BTreeMap>) -> Self { + pub fn new(set_map: BTreeMap>) -> Self { assert!( set_map.get(&0u64).is_some(), "ValidatorSet has to be specified from block 0." @@ -46,7 +47,7 @@ impl Multi { } } - fn correct_set(&self, id: BlockId) -> Option<&ValidatorSet> { + fn correct_set(&self, id: BlockId) -> Option<&dyn ValidatorSet> { match self.block_number.read()(id) .map(|parent_block| self.correct_set_by_number(parent_block)) { @@ -60,7 +61,7 @@ impl Multi { // get correct set by block number, along with block number at which // this set was activated. - fn correct_set_by_number(&self, parent_block: BlockNumber) -> (BlockNumber, &ValidatorSet) { + fn correct_set_by_number(&self, parent_block: BlockNumber) -> (BlockNumber, &dyn ValidatorSet) { let (block, set) = self.sets.iter() .rev() .find(|&(block, _)| *block <= parent_block + 1) @@ -165,7 +166,7 @@ impl ValidatorSet for Multi { .report_benign(validator, set_block, block); } - fn register_client(&self, client: Weak) { + fn register_client(&self, client: Weak) { for set in self.sets.values() { set.register_client(client.clone()); } @@ -263,7 +264,7 @@ mod tests { fn transition_to_fixed_list_instant() { use super::super::SimpleList; - let mut map: BTreeMap<_, Box> = BTreeMap::new(); + let mut map: BTreeMap<_, Box> = BTreeMap::new(); let list1: Vec<_> = (0..10).map(|_| Address::random()).collect(); let list2 = { let mut list = list1.clone(); diff --git a/ethcore/src/engines/validator_set/safe_contract.rs b/ethcore/src/engines/validator_set/safe_contract.rs index 9b9872598..14567fc9f 100644 --- a/ethcore/src/engines/validator_set/safe_contract.rs +++ b/ethcore/src/engines/validator_set/safe_contract.rs @@ -70,7 +70,7 @@ impl ::engines::StateDependentProof for StateProof { pub struct ValidatorSafeContract { contract_address: Address, validators: RwLock>, - client: RwLock>>, // TODO [keorn]: remove + client: RwLock>>, // TODO [keorn]: remove } // first proof is just a state proof call of `getValidators` at header's state. @@ -467,7 +467,7 @@ impl ValidatorSet for ValidatorSafeContract { }) } - fn register_client(&self, client: Weak) { + fn register_client(&self, client: Weak) { trace!(target: "engine", "Setting up contract caller."); *self.client.write() = Some(client); } diff --git a/ethcore/src/engines/validator_set/simple_list.rs b/ethcore/src/engines/validator_set/simple_list.rs index 6eeb02d61..e8d0b0159 100644 --- a/ethcore/src/engines/validator_set/simple_list.rs +++ b/ethcore/src/engines/validator_set/simple_list.rs @@ -114,8 +114,8 @@ impl ValidatorSet for SimpleList { } } -impl AsRef for SimpleList { - fn as_ref(&self) -> &ValidatorSet { +impl AsRef for SimpleList { + fn as_ref(&self) -> &dyn ValidatorSet { self } } diff --git a/ethcore/src/ethereum/ethash.rs b/ethcore/src/ethereum/ethash.rs index 6871a955c..4eefec67c 100644 --- a/ethcore/src/ethereum/ethash.rs +++ b/ethcore/src/ethereum/ethash.rs @@ -444,7 +444,7 @@ impl Engine for Arc { engines::ConstructedVerifier::Trusted(Box::new(self.clone())) } - fn snapshot_components(&self) -> Option> { + fn snapshot_components(&self) -> Option> { Some(Box::new(::snapshot::PowSnapshot::new( SNAPSHOT_BLOCKS, MAX_SNAPSHOT_BLOCKS, diff --git a/ethcore/src/executive.rs b/ethcore/src/executive.rs index 1731e630e..5164fa4d2 100644 --- a/ethcore/src/executive.rs +++ b/ethcore/src/executive.rs @@ -223,8 +223,8 @@ enum CallCreateExecutiveKind { CallBuiltin(ActionParams), ExecCall(ActionParams, Substate), ExecCreate(ActionParams, Substate), - ResumeCall(OriginInfo, Box, Substate), - ResumeCreate(OriginInfo, Box, Substate), + ResumeCall(OriginInfo, Box, Substate), + ResumeCreate(OriginInfo, Box, Substate), } /// Executive for a raw call/create action. diff --git a/ethcore/src/factory.rs b/ethcore/src/factory.rs index 444fa632b..e0e41f968 100644 --- a/ethcore/src/factory.rs +++ b/ethcore/src/factory.rs @@ -31,7 +31,7 @@ pub struct VmFactory { } impl VmFactory { - pub fn create(&self, params: ActionParams, schedule: &Schedule, depth: usize) -> Box { + pub fn create(&self, params: ActionParams, schedule: &Schedule, depth: usize) -> Box { if schedule.wasm.is_some() && params.code.as_ref().map_or(false, |code| { code.len() > 4 && &code[0..4] == WASM_MAGIC_NUMBER diff --git a/ethcore/src/machine/impls.rs b/ethcore/src/machine/impls.rs index a2ee16b3d..bf0bfede6 100644 --- a/ethcore/src/machine/impls.rs +++ b/ethcore/src/machine/impls.rs @@ -83,7 +83,7 @@ impl From<::ethjson::spec::EthashParams> for EthashExtensions { } /// Special rules to be applied to the schedule. -pub type ScheduleCreationRules = Fn(&mut Schedule, BlockNumber) + Sync + Send; +pub type ScheduleCreationRules = dyn Fn(&mut Schedule, BlockNumber) + Sync + Send; /// An ethereum-like state machine. pub struct EthereumMachine { @@ -479,7 +479,7 @@ pub struct AuxiliaryData<'a> { /// Type alias for a function we can make calls through synchronously. /// Returns the call result and state proof for each call. -pub type Call<'a> = Fn(Address, Vec) -> Result<(Vec, Vec>), String> + 'a; +pub type Call<'a> = dyn Fn(Address, Vec) -> Result<(Vec, Vec>), String> + 'a; /// Request for auxiliary data of a block. #[derive(Debug, Clone, Copy, PartialEq)] @@ -493,7 +493,7 @@ pub enum AuxiliaryRequest { } impl super::Machine for EthereumMachine { - type EngineClient = ::client::EngineClient; + type EngineClient = dyn crate::client::EngineClient; type Error = Error; diff --git a/ethcore/src/miner/miner.rs b/ethcore/src/miner/miner.rs index 5a0add234..f4a66cfec 100644 --- a/ethcore/src/miner/miner.rs +++ b/ethcore/src/miner/miner.rs @@ -206,7 +206,7 @@ pub enum Author { /// Sealing block is external and we only need a reward beneficiary (i.e. PoW) External(Address), /// Sealing is done internally, we need a way to create signatures to seal block (i.e. PoA) - Sealer(Box), + Sealer(Box), } impl Author { @@ -242,14 +242,14 @@ pub struct Miner { sealing: Mutex, params: RwLock, #[cfg(feature = "work-notify")] - listeners: RwLock>>, + listeners: RwLock>>, nonce_cache: NonceCache, gas_pricer: Mutex, options: MinerOptions, // TODO [ToDr] Arc is only required because of price updater transaction_queue: Arc, - engine: Arc, - accounts: Arc, + engine: Arc, + accounts: Arc, io_channel: RwLock>>, service_transaction_checker: Option, } @@ -257,13 +257,13 @@ pub struct Miner { impl Miner { /// Push listener that will handle new jobs #[cfg(feature = "work-notify")] - pub fn add_work_listener(&self, notifier: Box) { + pub fn add_work_listener(&self, notifier: Box) { self.listeners.write().push(notifier); self.sealing.lock().enabled = true; } /// Set a callback to be notified about imported transactions' hashes. - pub fn add_transactions_listener(&self, f: Box) { + pub fn add_transactions_listener(&self, f: Box) { self.transaction_queue.add_listener(f); } diff --git a/ethcore/src/miner/pool_client.rs b/ethcore/src/miner/pool_client.rs index 5946e2404..1ba729b38 100644 --- a/ethcore/src/miner/pool_client.rs +++ b/ethcore/src/miner/pool_client.rs @@ -66,8 +66,8 @@ impl NonceCache { pub struct PoolClient<'a, C: 'a> { chain: &'a C, cached_nonces: CachedNonceClient<'a, C>, - engine: &'a EthEngine, - accounts: &'a LocalAccounts, + engine: &'a dyn EthEngine, + accounts: &'a dyn LocalAccounts, best_block_header: Header, service_transaction_checker: Option<&'a ServiceTransactionChecker>, } @@ -93,8 +93,8 @@ where pub fn new( chain: &'a C, cache: &'a NonceCache, - engine: &'a EthEngine, - accounts: &'a LocalAccounts, + engine: &'a dyn EthEngine, + accounts: &'a dyn LocalAccounts, service_transaction_checker: Option<&'a ServiceTransactionChecker>, ) -> Self { let best_block_header = chain.best_block_header(); diff --git a/ethcore/src/miner/stratum.rs b/ethcore/src/miner/stratum.rs index 4dfaa2151..4e7eec747 100644 --- a/ethcore/src/miner/stratum.rs +++ b/ethcore/src/miner/stratum.rs @@ -263,7 +263,7 @@ impl Stratum { #[cfg(feature = "work-notify")] pub fn register(cfg: &Options, miner: Arc, client: Weak) -> Result<(), Error> { let stratum = Stratum::start(cfg, Arc::downgrade(&miner.clone()), client)?; - miner.add_work_listener(Box::new(stratum) as Box); + miner.add_work_listener(Box::new(stratum) as Box); Ok(()) } } diff --git a/ethcore/src/pod_account.rs b/ethcore/src/pod_account.rs index 0aac929a5..4878273a3 100644 --- a/ethcore/src/pod_account.rs +++ b/ethcore/src/pod_account.rs @@ -94,7 +94,7 @@ impl PodAccount { /// Place additional data into given hash DB. pub fn insert_additional( &self, - db: &mut HashDB, + db: &mut dyn HashDB, factory: &TrieFactory, ) { match self.code { diff --git a/ethcore/src/snapshot/consensus/authority.rs b/ethcore/src/snapshot/consensus/authority.rs index c38f95b9f..71b2bb10a 100644 --- a/ethcore/src/snapshot/consensus/authority.rs +++ b/ethcore/src/snapshot/consensus/authority.rs @@ -131,9 +131,9 @@ impl SnapshotComponents for PoaSnapshot { fn rebuilder( &self, chain: BlockChain, - db: Arc, + db: Arc, manifest: &ManifestData, - ) -> Result, ::error::Error> { + ) -> Result, ::error::Error> { Ok(Box::new(ChunkRebuilder { manifest: manifest.clone(), warp_target: None, @@ -172,14 +172,14 @@ struct ChunkRebuilder { manifest: ManifestData, warp_target: Option
, chain: BlockChain, - db: Arc, + db: Arc, had_genesis: bool, // sorted vectors of unverified first blocks in a chunk // and epoch data from last blocks in chunks. // verification for these will be done at the end. unverified_firsts: Vec<(Header, Bytes, H256)>, - last_epochs: Vec<(Header, Box>)>, + last_epochs: Vec<(Header, Box>)>, } // verified data. @@ -191,9 +191,9 @@ struct Verified { impl ChunkRebuilder { fn verify_transition( &mut self, - last_verifier: &mut Option>>, + last_verifier: &mut Option>>, transition_rlp: Rlp, - engine: &EthEngine, + engine: &dyn EthEngine, ) -> Result { use engines::ConstructedVerifier; @@ -253,7 +253,7 @@ impl Rebuilder for ChunkRebuilder { fn feed( &mut self, chunk: &[u8], - engine: &EthEngine, + engine: &dyn EthEngine, abort_flag: &AtomicBool, ) -> Result<(), ::error::Error> { let rlp = Rlp::new(chunk); @@ -384,7 +384,7 @@ impl Rebuilder for ChunkRebuilder { Ok(()) } - fn finalize(&mut self, _engine: &EthEngine) -> Result<(), ::error::Error> { + fn finalize(&mut self, _engine: &dyn EthEngine) -> Result<(), ::error::Error> { if !self.had_genesis { return Err(Error::WrongChunkFormat("No genesis transition included.".into()).into()); } diff --git a/ethcore/src/snapshot/consensus/mod.rs b/ethcore/src/snapshot/consensus/mod.rs index 8ec76ad63..79924a549 100644 --- a/ethcore/src/snapshot/consensus/mod.rs +++ b/ethcore/src/snapshot/consensus/mod.rs @@ -31,7 +31,7 @@ mod work; pub use self::{authority::*, work::*}; /// A sink for produced chunks. -pub type ChunkSink<'a> = FnMut(&[u8]) -> ::std::io::Result<()> + 'a; +pub type ChunkSink<'a> = dyn FnMut(&[u8]) -> ::std::io::Result<()> + 'a; /// Components necessary for snapshot creation and restoration. pub trait SnapshotComponents: Send { @@ -61,9 +61,9 @@ pub trait SnapshotComponents: Send { fn rebuilder( &self, chain: BlockChain, - db: Arc, + db: Arc, manifest: &ManifestData, - ) -> Result, ::error::Error>; + ) -> Result, ::error::Error>; /// Minimum supported snapshot version number. fn min_supported_version(&self) -> u64; @@ -81,7 +81,7 @@ pub trait Rebuilder: Send { fn feed( &mut self, chunk: &[u8], - engine: &EthEngine, + engine: &dyn EthEngine, abort_flag: &AtomicBool, ) -> Result<(), ::error::Error>; @@ -90,5 +90,5 @@ pub trait Rebuilder: Send { /// /// This should apply the necessary "glue" between chunks, /// and verify against the restored state. - fn finalize(&mut self, engine: &EthEngine) -> Result<(), ::error::Error>; + fn finalize(&mut self, engine: &dyn EthEngine) -> Result<(), ::error::Error>; } diff --git a/ethcore/src/snapshot/consensus/work.rs b/ethcore/src/snapshot/consensus/work.rs index 5a81eeabc..f6c9d26c0 100644 --- a/ethcore/src/snapshot/consensus/work.rs +++ b/ethcore/src/snapshot/consensus/work.rs @@ -85,9 +85,9 @@ impl SnapshotComponents for PowSnapshot { fn rebuilder( &self, chain: BlockChain, - db: Arc, + db: Arc, manifest: &ManifestData, - ) -> Result, ::error::Error> { + ) -> Result, ::error::Error> { PowRebuilder::new( chain, db.key_value().clone(), @@ -221,7 +221,7 @@ impl<'a> PowWorker<'a> { /// After all chunks have been submitted, we "glue" the chunks together. pub struct PowRebuilder { chain: BlockChain, - db: Arc, + db: Arc, rng: OsRng, disconnected: Vec<(u64, H256)>, best_number: u64, @@ -235,7 +235,7 @@ impl PowRebuilder { /// Create a new PowRebuilder. fn new( chain: BlockChain, - db: Arc, + db: Arc, manifest: &ManifestData, snapshot_blocks: u64, ) -> Result { @@ -259,7 +259,7 @@ impl Rebuilder for PowRebuilder { fn feed( &mut self, chunk: &[u8], - engine: &EthEngine, + engine: &dyn EthEngine, abort_flag: &AtomicBool, ) -> Result<(), ::error::Error> { use ethereum_types::U256; @@ -354,7 +354,7 @@ impl Rebuilder for PowRebuilder { } /// Glue together any disconnected chunks and check that the chain is complete. - fn finalize(&mut self, _: &EthEngine) -> Result<(), ::error::Error> { + fn finalize(&mut self, _: &dyn EthEngine) -> Result<(), ::error::Error> { let mut batch = self.db.transaction(); for (first_num, first_hash) in self.disconnected.drain(..) { diff --git a/ethcore/src/snapshot/service.rs b/ethcore/src/snapshot/service.rs index 30c69f909..46acf9474 100644 --- a/ethcore/src/snapshot/service.rs +++ b/ethcore/src/snapshot/service.rs @@ -88,22 +88,22 @@ struct Restoration { state_chunks_left: HashSet, block_chunks_left: HashSet, state: StateRebuilder, - secondary: Box, + secondary: Box, writer: Option, snappy_buffer: Bytes, final_state_root: H256, guard: Guard, - db: Arc, + db: Arc, } struct RestorationParams<'a> { manifest: ManifestData, // manifest to base restoration on. pruning: Algorithm, // pruning algorithm for the database. - db: Arc, // database + db: Arc, // database writer: Option, // writer for recovered snapshot. genesis: &'a [u8], // genesis block of the chain. guard: Guard, // guard for the restoration directory. - engine: &'a EthEngine, + engine: &'a dyn EthEngine, } impl Restoration { @@ -167,7 +167,7 @@ impl Restoration { &mut self, hash: H256, chunk: &[u8], - engine: &EthEngine, + engine: &dyn EthEngine, flag: &AtomicBool, ) -> Result<(), Error> { if self.block_chunks_left.contains(&hash) { @@ -191,7 +191,7 @@ impl Restoration { } // finish up restoration. - fn finalize(mut self, engine: &EthEngine) -> Result<(), Error> { + fn finalize(mut self, engine: &dyn EthEngine) -> Result<(), Error> { use trie::TrieError; if !self.is_done() { @@ -238,37 +238,37 @@ pub trait SnapshotClient: BlockChainClient + BlockInfo + DatabaseRestore {} /// Snapshot service parameters. pub struct ServiceParams { /// The consensus engine this is built on. - pub engine: Arc, + pub engine: Arc, /// The chain's genesis block. pub genesis_block: Bytes, /// State pruning algorithm. pub pruning: Algorithm, /// Handler for opening a restoration DB. - pub restoration_db_handler: Box, + pub restoration_db_handler: Box, /// Async IO channel for sending messages. pub channel: Channel, /// The directory to put snapshots in. /// Usually "/snapshot" pub snapshot_root: PathBuf, /// A handle for database restoration. - pub client: Arc, + pub client: Arc, } /// `SnapshotService` implementation. /// This controls taking snapshots and restoring from them. pub struct Service { restoration: Mutex>, - restoration_db_handler: Box, + restoration_db_handler: Box, snapshot_root: PathBuf, io_channel: Mutex, pruning: Algorithm, status: Mutex, reader: RwLock>, - engine: Arc, + engine: Arc, genesis_block: Bytes, state_chunks: AtomicUsize, block_chunks: AtomicUsize, - client: Arc, + client: Arc, progress: super::Progress, taking_snapshot: AtomicBool, restoring_snapshot: AtomicBool, diff --git a/ethcore/src/snapshot/tests/helpers.rs b/ethcore/src/snapshot/tests/helpers.rs index 7e117ad77..781eb7799 100644 --- a/ethcore/src/snapshot/tests/helpers.rs +++ b/ethcore/src/snapshot/tests/helpers.rs @@ -64,7 +64,7 @@ impl StateProducer { /// Tick the state producer. This alters the state, writing new data into /// the database. - pub fn tick(&mut self, rng: &mut R, db: &mut HashDB) { + pub fn tick(&mut self, rng: &mut R, db: &mut dyn HashDB) { // modify existing accounts. let mut accounts_to_modify: Vec<_> = { let trie = TrieDB::new(&db, &self.state_root).unwrap(); @@ -137,7 +137,7 @@ pub fn fill_storage(mut db: AccountDBMut, root: &mut H256, seed: &mut H256) { /// Take a snapshot from the given client into a temporary file. /// Return a snapshot reader for it. -pub fn snap(client: &Client) -> (Box, TempDir) { +pub fn snap(client: &Client) -> (Box, TempDir) { use types::ids::BlockId; let tempdir = TempDir::new("").unwrap(); @@ -158,9 +158,9 @@ pub fn snap(client: &Client) -> (Box, TempDir) { /// Restore a snapshot into a given database. This will read chunks from the given reader /// write into the given database. pub fn restore( - db: Arc, - engine: &EthEngine, - reader: &SnapshotReader, + db: Arc, + engine: &dyn EthEngine, + reader: &dyn SnapshotReader, genesis: &[u8], ) -> Result<(), ::error::Error> { use snappy; diff --git a/ethcore/src/snapshot/watcher.rs b/ethcore/src/snapshot/watcher.rs index e65be7eaf..074a0d26e 100644 --- a/ethcore/src/snapshot/watcher.rs +++ b/ethcore/src/snapshot/watcher.rs @@ -78,8 +78,8 @@ impl Broadcast for Mutex> { /// A `ChainNotify` implementation which will trigger a snapshot event /// at certain block numbers. pub struct Watcher { - oracle: Box, - broadcast: Box, + oracle: Box, + broadcast: Box, period: u64, history: u64, } diff --git a/ethcore/src/spec/spec.rs b/ethcore/src/spec/spec.rs index d56d7d7b0..e46eb8a44 100644 --- a/ethcore/src/spec/spec.rs +++ b/ethcore/src/spec/spec.rs @@ -402,7 +402,7 @@ pub struct Spec { /// User friendly spec name pub name: String, /// What engine are we using for this? - pub engine: Arc, + pub engine: Arc, /// Name of the subdir inside the main data dir to use for chain data and settings. pub data_dir: String, @@ -642,7 +642,7 @@ impl Spec { engine_spec: ethjson::spec::Engine, params: CommonParams, builtins: BTreeMap, - ) -> Arc { + ) -> Arc { let machine = Self::machine(&engine_spec, params, builtins); match engine_spec { diff --git a/ethcore/src/state/account.rs b/ethcore/src/state/account.rs index 581d7305d..a9757863b 100644 --- a/ethcore/src/state/account.rs +++ b/ethcore/src/state/account.rs @@ -225,7 +225,11 @@ impl Account { /// Get (and cache) the contents of the trie's storage at `key`. /// Takes modified storage into account. - pub fn storage_at(&self, db: &HashDB, key: &H256) -> TrieResult { + pub fn storage_at( + &self, + db: &dyn HashDB, + key: &H256, + ) -> TrieResult { if let Some(value) = self.cached_storage_at(key) { return Ok(value); } @@ -241,7 +245,7 @@ impl Account { /// Does not take modified storage into account. pub fn original_storage_at( &self, - db: &HashDB, + db: &dyn HashDB, key: &H256, ) -> TrieResult { if let Some(value) = self.cached_original_storage_at(key) { @@ -268,7 +272,7 @@ impl Account { fn get_and_cache_storage( storage_root: &H256, storage_cache: &mut LruCache, - db: &HashDB, + db: &dyn HashDB, key: &H256, ) -> TrieResult { let db = SecTrieDB::new(&db, storage_root)?; @@ -382,7 +386,7 @@ impl Account { /// Provide a database to get `code_hash`. Should not be called if it is a contract without code. Returns the cached code, if successful. #[must_use] - pub fn cache_code(&mut self, db: &HashDB) -> Option> { + pub fn cache_code(&mut self, db: &dyn HashDB) -> Option> { // TODO: fill out self.code_cache; trace!( "Account::cache_code: ic={}; self.code_hash={:?}, self.code_cache={}", @@ -424,7 +428,7 @@ impl Account { /// Provide a database to get `code_size`. Should not be called if it is a contract without code. Returns whether /// the cache succeeds. #[must_use] - pub fn cache_code_size(&mut self, db: &HashDB) -> bool { + pub fn cache_code_size(&mut self, db: &dyn HashDB) -> bool { // TODO: fill out self.code_cache; trace!( "Account::cache_code_size: ic={}; self.code_hash={:?}, self.code_cache={}", @@ -531,7 +535,7 @@ impl Account { pub fn commit_storage( &mut self, trie_factory: &TrieFactory, - db: &mut HashDB, + db: &mut dyn HashDB, ) -> TrieResult<()> { let mut t = trie_factory.from_existing(db, &mut self.storage_root)?; for (k, v) in self.storage_changes.drain() { @@ -549,7 +553,7 @@ impl Account { } /// Commit any unsaved code. `code_hash` will always return the hash of the `code_cache` after this. - pub fn commit_code(&mut self, db: &mut HashDB) { + pub fn commit_code(&mut self, db: &mut dyn HashDB) { trace!( "Commiting code of {:?} - {:?}, {:?}", self, @@ -651,7 +655,7 @@ impl Account { /// this will only work correctly under a secure trie. pub fn prove_storage( &self, - db: &HashDB, + db: &dyn HashDB, storage_key: H256, ) -> TrieResult<(Vec, H256)> { let mut recorder = Recorder::new(); diff --git a/ethcore/src/state/backend.rs b/ethcore/src/state/backend.rs index e2d9c4d70..001083a9d 100644 --- a/ethcore/src/state/backend.rs +++ b/ethcore/src/state/backend.rs @@ -38,10 +38,10 @@ use state::Account; /// State backend. See module docs for more details. pub trait Backend: Send { /// Treat the backend as a read-only hashdb. - fn as_hash_db(&self) -> &HashDB; + fn as_hash_db(&self) -> &dyn HashDB; /// Treat the backend as a writeable hashdb. - fn as_hash_db_mut(&mut self) -> &mut HashDB; + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB; /// Add an account entry to the cache. fn add_to_account_cache(&mut self, addr: Address, data: Option, modified: bool); @@ -121,19 +121,19 @@ impl HashDB for ProofCheck { } impl AsHashDB for ProofCheck { - fn as_hash_db(&self) -> &HashDB { + fn as_hash_db(&self) -> &dyn HashDB { self } - fn as_hash_db_mut(&mut self) -> &mut HashDB { + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self } } impl Backend for ProofCheck { - fn as_hash_db(&self) -> &HashDB { + fn as_hash_db(&self) -> &dyn HashDB { self } - fn as_hash_db_mut(&mut self) -> &mut HashDB { + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self } fn add_to_account_cache(&mut self, _addr: Address, _data: Option, _modified: bool) {} @@ -168,7 +168,7 @@ pub struct Proving { } impl AsKeyedHashDB for Proving { - fn as_keyed_hash_db(&self) -> &journaldb::KeyedHashDB { + fn as_keyed_hash_db(&self) -> &dyn journaldb::KeyedHashDB { self } } @@ -176,10 +176,10 @@ impl AsKeyedHashDB for Proving { impl + Send + Sync> AsHashDB for Proving { - fn as_hash_db(&self) -> &HashDB { + fn as_hash_db(&self) -> &dyn HashDB { self } - fn as_hash_db_mut(&mut self) -> &mut HashDB { + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self } } @@ -226,11 +226,11 @@ impl + Send + Sync> HashDB + Send + Sync> Backend for Proving { - fn as_hash_db(&self) -> &HashDB { + fn as_hash_db(&self) -> &dyn HashDB { self } - fn as_hash_db_mut(&mut self) -> &mut HashDB { + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self } @@ -291,11 +291,11 @@ impl + Clone> Clone for Proving { pub struct Basic(pub H); impl + Send + Sync> Backend for Basic { - fn as_hash_db(&self) -> &HashDB { + fn as_hash_db(&self) -> &dyn HashDB { self.0.as_hash_db() } - fn as_hash_db_mut(&mut self) -> &mut HashDB { + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self.0.as_hash_db_mut() } diff --git a/ethcore/src/state/mod.rs b/ethcore/src/state/mod.rs index 283099496..7efbf22e0 100644 --- a/ethcore/src/state/mod.rs +++ b/ethcore/src/state/mod.rs @@ -702,7 +702,7 @@ impl State { ) -> TrieResult where FCachedStorageAt: Fn(&Account, &H256) -> Option, - FStorageAt: Fn(&Account, &HashDB, &H256) -> TrieResult, + FStorageAt: Fn(&Account, &dyn HashDB, &H256) -> TrieResult, { // Storage key search and update works like this: // 1. If there's an entry for the account in the local cache check for the key and return it if found. @@ -1287,7 +1287,7 @@ impl State { require: RequireCache, account: &mut Account, state_db: &B, - db: &HashDB, + db: &dyn HashDB, ) -> bool { if let RequireCache::None = require { return true; diff --git a/ethcore/src/state_db.rs b/ethcore/src/state_db.rs index 1103eb01c..42cd0c71c 100644 --- a/ethcore/src/state_db.rs +++ b/ethcore/src/state_db.rs @@ -109,7 +109,7 @@ struct BlockChanges { /// `StateDB` is propagated into the global cache. pub struct StateDB { /// Backing database. - db: Box, + db: Box, /// Shared canonical state cache. account_cache: Arc>, /// DB Code cache. Maps code hashes to shared bytes. @@ -133,7 +133,7 @@ impl StateDB { /// of the LRU cache in bytes. Actual used memory may (read: will) be higher due to bookkeeping. // TODO: make the cache size actually accurate by moving the account storage cache // into the `AccountCache` structure as its own `LruCache<(Address, H256), H256>`. - pub fn new(db: Box, cache_size: usize) -> StateDB { + pub fn new(db: Box, cache_size: usize) -> StateDB { let bloom = Self::load_bloom(&**db.backing()); let acc_cache_size = cache_size * ACCOUNT_CACHE_RATIO / 100; let code_cache_size = cache_size - acc_cache_size; @@ -157,7 +157,7 @@ impl StateDB { /// Loads accounts bloom from the database /// This bloom is used to handle request for the non-existant account fast - pub fn load_bloom(db: &KeyValueDB) -> Bloom { + pub fn load_bloom(db: &dyn KeyValueDB) -> Bloom { let hash_count_entry = db .get(COL_ACCOUNT_BLOOM, ACCOUNT_BLOOM_HASHCOUNT_KEY) .expect("Low-level database error"); @@ -349,12 +349,12 @@ impl StateDB { } /// Conversion method to interpret self as `HashDB` reference - pub fn as_hash_db(&self) -> &HashDB { + pub fn as_hash_db(&self) -> &dyn HashDB { self.db.as_hash_db() } /// Conversion method to interpret self as mutable `HashDB` reference - pub fn as_hash_db_mut(&mut self) -> &mut HashDB { + pub fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self.db.as_hash_db_mut() } @@ -404,7 +404,7 @@ impl StateDB { } /// Returns underlying `JournalDB`. - pub fn journal_db(&self) -> &JournalDB { + pub fn journal_db(&self) -> &dyn JournalDB { &*self.db } @@ -453,11 +453,11 @@ impl StateDB { } impl state::Backend for StateDB { - fn as_hash_db(&self) -> &HashDB { + fn as_hash_db(&self) -> &dyn HashDB { self.db.as_hash_db() } - fn as_hash_db_mut(&mut self) -> &mut HashDB { + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self.db.as_hash_db_mut() } diff --git a/ethcore/src/test_helpers.rs b/ethcore/src/test_helpers.rs index d3a58096b..106f44c54 100644 --- a/ethcore/src/test_helpers.rs +++ b/ethcore/src/test_helpers.rs @@ -333,11 +333,11 @@ struct TestBlockChainDB { _trace_blooms_dir: TempDir, blooms: blooms_db::Database, trace_blooms: blooms_db::Database, - key_value: Arc, + key_value: Arc, } impl BlockChainDB for TestBlockChainDB { - fn key_value(&self) -> &Arc { + fn key_value(&self) -> &Arc { &self.key_value } @@ -351,7 +351,7 @@ impl BlockChainDB for TestBlockChainDB { } /// Creates new test instance of `BlockChainDB` -pub fn new_db() -> Arc { +pub fn new_db() -> Arc { let blooms_dir = TempDir::new("").unwrap(); let trace_blooms_dir = TempDir::new("").unwrap(); @@ -367,7 +367,7 @@ pub fn new_db() -> Arc { } /// Creates a new temporary `BlockChainDB` on FS -pub fn new_temp_db(tempdir: &Path) -> Arc { +pub fn new_temp_db(tempdir: &Path) -> Arc { let blooms_dir = TempDir::new("").unwrap(); let trace_blooms_dir = TempDir::new("").unwrap(); let key_value_dir = tempdir.join("key_value"); @@ -387,7 +387,9 @@ pub fn new_temp_db(tempdir: &Path) -> Arc { } /// Creates new instance of KeyValueDBHandler -pub fn restoration_db_handler(config: kvdb_rocksdb::DatabaseConfig) -> Box { +pub fn restoration_db_handler( + config: kvdb_rocksdb::DatabaseConfig, +) -> Box { struct RestorationDBHandler { config: kvdb_rocksdb::DatabaseConfig, } @@ -395,11 +397,11 @@ pub fn restoration_db_handler(config: kvdb_rocksdb::DatabaseConfig) -> Box, + key_value: Arc, } impl BlockChainDB for RestorationDB { - fn key_value(&self) -> &Arc { + fn key_value(&self) -> &Arc { &self.key_value } @@ -413,7 +415,7 @@ pub fn restoration_db_handler(config: kvdb_rocksdb::DatabaseConfig) -> Box io::Result> { + fn open(&self, db_path: &Path) -> io::Result> { let key_value = Arc::new(kvdb_rocksdb::Database::open( &self.config, &db_path.to_string_lossy(), diff --git a/ethcore/src/trace/db.rs b/ethcore/src/trace/db.rs index f5325e668..8cafac711 100644 --- a/ethcore/src/trace/db.rs +++ b/ethcore/src/trace/db.rs @@ -64,7 +64,7 @@ where /// hashes of cached traces cache_manager: RwLock>, /// db - db: Arc, + db: Arc, /// tracing enabled enabled: bool, /// extras @@ -76,7 +76,7 @@ where T: DatabaseExtras, { /// Creates new instance of `TraceDB`. - pub fn new(config: Config, db: Arc, extras: Arc) -> Self { + pub fn new(config: Config, db: Arc, extras: Arc) -> Self { let mut batch = DBTransaction::new(); let genesis = extras .block_hash(0) diff --git a/ethcore/src/verification/canon_verifier.rs b/ethcore/src/verification/canon_verifier.rs index de7407d37..d02a7643f 100644 --- a/ethcore/src/verification/canon_verifier.rs +++ b/ethcore/src/verification/canon_verifier.rs @@ -31,7 +31,7 @@ impl Verifier for CanonVerifier { &self, header: &Header, parent: &Header, - engine: &EthEngine, + engine: &dyn EthEngine, do_full: Option>, ) -> Result<(), Error> { verification::verify_block_family(header, parent, engine, do_full) @@ -41,7 +41,7 @@ impl Verifier for CanonVerifier { verification::verify_block_final(expected, got) } - fn verify_block_external(&self, header: &Header, engine: &EthEngine) -> Result<(), Error> { + fn verify_block_external(&self, header: &Header, engine: &dyn EthEngine) -> Result<(), Error> { engine.verify_block_external(header) } } diff --git a/ethcore/src/verification/mod.rs b/ethcore/src/verification/mod.rs index 8022c3a4b..6e957e371 100644 --- a/ethcore/src/verification/mod.rs +++ b/ethcore/src/verification/mod.rs @@ -46,7 +46,7 @@ pub enum VerifierType { } /// Create a new verifier based on type. -pub fn new(v: VerifierType) -> Box> { +pub fn new(v: VerifierType) -> Box> { match v { VerifierType::Canon | VerifierType::CanonNoSeal => Box::new(CanonVerifier), VerifierType::Noop => Box::new(NoopVerifier), diff --git a/ethcore/src/verification/noop_verifier.rs b/ethcore/src/verification/noop_verifier.rs index 7da110094..5e922bfa5 100644 --- a/ethcore/src/verification/noop_verifier.rs +++ b/ethcore/src/verification/noop_verifier.rs @@ -32,7 +32,7 @@ impl Verifier for NoopVerifier { &self, _: &Header, _t: &Header, - _: &EthEngine, + _: &dyn EthEngine, _: Option>, ) -> Result<(), Error> { Ok(()) @@ -42,7 +42,11 @@ impl Verifier for NoopVerifier { Ok(()) } - fn verify_block_external(&self, _header: &Header, _engine: &EthEngine) -> Result<(), Error> { + fn verify_block_external( + &self, + _header: &Header, + _engine: &dyn EthEngine, + ) -> Result<(), Error> { Ok(()) } } diff --git a/ethcore/src/verification/queue/kind.rs b/ethcore/src/verification/queue/kind.rs index c57543760..ce6569d10 100644 --- a/ethcore/src/verification/queue/kind.rs +++ b/ethcore/src/verification/queue/kind.rs @@ -62,14 +62,14 @@ pub trait Kind: 'static + Sized + Send + Sync { /// Attempt to create the `Unverified` item from the input. fn create( input: Self::Input, - engine: &EthEngine, + engine: &dyn EthEngine, check_seal: bool, ) -> Result; /// Attempt to verify the `Unverified` item using the given engine. fn verify( unverified: Self::Unverified, - engine: &EthEngine, + engine: &dyn EthEngine, check_seal: bool, ) -> Result; } @@ -97,7 +97,7 @@ pub mod blocks { fn create( input: Self::Input, - engine: &EthEngine, + engine: &dyn EthEngine, check_seal: bool, ) -> Result { match verify_block_basic(&input, engine, check_seal) { @@ -115,7 +115,7 @@ pub mod blocks { fn verify( un: Self::Unverified, - engine: &EthEngine, + engine: &dyn EthEngine, check_seal: bool, ) -> Result { let hash = un.hash(); @@ -245,7 +245,7 @@ pub mod headers { fn create( input: Self::Input, - engine: &EthEngine, + engine: &dyn EthEngine, check_seal: bool, ) -> Result { match verify_header_params(&input, engine, true, check_seal) { @@ -256,7 +256,7 @@ pub mod headers { fn verify( unverified: Self::Unverified, - engine: &EthEngine, + engine: &dyn EthEngine, check_seal: bool, ) -> Result { match check_seal { diff --git a/ethcore/src/verification/queue/mod.rs b/ethcore/src/verification/queue/mod.rs index 6cc52cadb..e9d957140 100644 --- a/ethcore/src/verification/queue/mod.rs +++ b/ethcore/src/verification/queue/mod.rs @@ -142,7 +142,7 @@ struct Sizes { /// A queue of items to be verified. Sits between network or other I/O and the `BlockChain`. /// Keeps them in the same order as inserted, minus invalid items. pub struct VerificationQueue { - engine: Arc, + engine: Arc, more_to_verify: Arc, verification: Arc>, deleting: Arc, @@ -220,7 +220,7 @@ impl VerificationQueue { /// Creates a new queue instance. pub fn new( config: Config, - engine: Arc, + engine: Arc, message_channel: IoChannel, check_seal: bool, ) -> Self { @@ -305,7 +305,7 @@ impl VerificationQueue { fn verify( verification: Arc>, - engine: Arc, + engine: Arc, wait: Arc, ready: Arc, empty: Arc, diff --git a/ethcore/src/verification/verification.rs b/ethcore/src/verification/verification.rs index 4ff9d211f..b5c3ff58d 100644 --- a/ethcore/src/verification/verification.rs +++ b/ethcore/src/verification/verification.rs @@ -66,7 +66,7 @@ impl HeapSizeOf for PreverifiedBlock { /// Phase 1 quick block verification. Only does checks that are cheap. Operates on a single block pub fn verify_block_basic( block: &Unverified, - engine: &EthEngine, + engine: &dyn EthEngine, check_seal: bool, ) -> Result<(), Error> { verify_header_params(&block.header, engine, true, check_seal)?; @@ -95,7 +95,7 @@ pub fn verify_block_basic( /// Returns a `PreverifiedBlock` structure populated with transactions pub fn verify_block_unordered( block: Unverified, - engine: &EthEngine, + engine: &dyn EthEngine, check_seal: bool, ) -> Result { let header = block.header; @@ -140,7 +140,7 @@ pub struct FullFamilyParams<'a, C: BlockInfo + CallContract + 'a> { pub block: &'a PreverifiedBlock, /// Block provider to use during verification - pub block_provider: &'a BlockProvider, + pub block_provider: &'a dyn BlockProvider, /// Engine client to use during verification pub client: &'a C, @@ -150,7 +150,7 @@ pub struct FullFamilyParams<'a, C: BlockInfo + CallContract + 'a> { pub fn verify_block_family( header: &Header, parent: &Header, - engine: &EthEngine, + engine: &dyn EthEngine, do_full: Option>, ) -> Result<(), Error> { // TODO: verify timestamp @@ -177,8 +177,8 @@ pub fn verify_block_family( fn verify_uncles( block: &PreverifiedBlock, - bc: &BlockProvider, - engine: &EthEngine, + bc: &dyn BlockProvider, + engine: &dyn EthEngine, ) -> Result<(), Error> { let header = &block.header; let num_uncles = block.uncles.len(); @@ -319,7 +319,7 @@ pub fn verify_block_final(expected: &Header, got: &Header) -> Result<(), Error> /// Check basic header parameters. pub fn verify_header_params( header: &Header, - engine: &EthEngine, + engine: &dyn EthEngine, is_full: bool, check_seal: bool, ) -> Result<(), Error> { @@ -418,7 +418,7 @@ pub fn verify_header_params( } /// Check header parameters agains parent header. -fn verify_parent(header: &Header, parent: &Header, engine: &EthEngine) -> Result<(), Error> { +fn verify_parent(header: &Header, parent: &Header, engine: &dyn EthEngine) -> Result<(), Error> { assert!( header.parent_hash().is_zero() || &parent.hash() == header.parent_hash(), "Parent hash should already have been verified; qed" @@ -661,12 +661,12 @@ mod tests { } } - fn basic_test(bytes: &[u8], engine: &EthEngine) -> Result<(), Error> { + fn basic_test(bytes: &[u8], engine: &dyn EthEngine) -> Result<(), Error> { let unverified = Unverified::from_rlp(bytes.to_vec())?; verify_block_basic(&unverified, engine, true) } - fn family_test(bytes: &[u8], engine: &EthEngine, bc: &BC) -> Result<(), Error> + fn family_test(bytes: &[u8], engine: &dyn EthEngine, bc: &BC) -> Result<(), Error> where BC: BlockProvider, { @@ -697,13 +697,13 @@ mod tests { let full_params = FullFamilyParams { block: &block, - block_provider: bc as &BlockProvider, + block_provider: bc as &dyn BlockProvider, client: &client, }; verify_block_family(&block.header, &parent, engine, Some(full_params)) } - fn unordered_test(bytes: &[u8], engine: &EthEngine) -> Result<(), Error> { + fn unordered_test(bytes: &[u8], engine: &dyn EthEngine) -> Result<(), Error> { let un = Unverified::from_rlp(bytes.to_vec())?; verify_block_unordered(un, engine, false)?; Ok(()) diff --git a/ethcore/src/verification/verifier.rs b/ethcore/src/verification/verifier.rs index 8f5cdd7d4..7383ac60d 100644 --- a/ethcore/src/verification/verifier.rs +++ b/ethcore/src/verification/verifier.rs @@ -33,12 +33,12 @@ where &self, header: &Header, parent: &Header, - engine: &EthEngine, + engine: &dyn EthEngine, do_full: Option>, ) -> Result<(), Error>; /// Do a final verification check for an enacted header vs its expected counterpart. fn verify_block_final(&self, expected: &Header, got: &Header) -> Result<(), Error>; /// Verify a block, inspecing external state. - fn verify_block_external(&self, header: &Header, engine: &EthEngine) -> Result<(), Error>; + fn verify_block_external(&self, header: &Header, engine: &dyn EthEngine) -> Result<(), Error>; } diff --git a/ethcore/sync/src/api.rs b/ethcore/sync/src/api.rs index 69c5dfaaa..6bd358508 100644 --- a/ethcore/sync/src/api.rs +++ b/ethcore/sync/src/api.rs @@ -218,7 +218,7 @@ impl From for PipProtocolInfo { /// Only works when IPC is disabled. pub struct AttachedProtocol { /// The protocol handler in question. - pub handler: Arc, + pub handler: Arc, /// 3-character ID for the protocol. pub protocol_id: ProtocolId, /// Supported versions and their packet counts. @@ -273,13 +273,13 @@ pub struct Params { /// Configuration. pub config: SyncConfig, /// Blockchain client. - pub chain: Arc, + pub chain: Arc, /// Snapshot service. - pub snapshot_service: Arc, + pub snapshot_service: Arc, /// Private tx service. - pub private_tx_handler: Option>, + pub private_tx_handler: Option>, /// Light data provider. - pub provider: Arc<::light::Provider>, + pub provider: Arc, /// Network layer configuration. pub network_config: NetworkConfiguration, /// Other protocols to attach. @@ -308,7 +308,7 @@ fn light_params( network_id: u64, median_peers: f64, pruning_info: PruningInfo, - sample_store: Option>, + sample_store: Option>, ) -> LightParams { let mut light_params = LightParams { network_id: network_id, @@ -330,7 +330,7 @@ impl EthSync { /// Creates and register protocol with the network service pub fn new( params: Params, - connection_filter: Option>, + connection_filter: Option>, ) -> Result, Error> { let pruning_info = params.chain.pruning_info(); let light_proto = match params.config.serve_light { @@ -464,9 +464,9 @@ pub(crate) const PRIORITY_TIMER_INTERVAL: Duration = Duration::from_millis(250); struct SyncProtocolHandler { /// Shared blockchain client. - chain: Arc, + chain: Arc, /// Shared snapshot service. - snapshot_service: Arc, + snapshot_service: Arc, /// Sync strategy sync: ChainSyncApi, /// Chain overlay used to cache data such as fork block. @@ -474,7 +474,7 @@ struct SyncProtocolHandler { } impl NetworkProtocolHandler for SyncProtocolHandler { - fn initialize(&self, io: &NetworkContext) { + fn initialize(&self, io: &dyn NetworkContext) { if io.subprotocol_name() != WARP_SYNC_PROTOCOL_ID { io.register_timer(PEERS_TIMER, Duration::from_millis(700)) .expect("Error registering peers timer"); @@ -490,7 +490,7 @@ impl NetworkProtocolHandler for SyncProtocolHandler { } } - fn read(&self, io: &NetworkContext, peer: &PeerId, packet_id: u8, data: &[u8]) { + fn read(&self, io: &dyn NetworkContext, peer: &PeerId, packet_id: u8, data: &[u8]) { self.sync.dispatch_packet( &mut NetSyncIo::new(io, &*self.chain, &*self.snapshot_service, &self.overlay), *peer, @@ -499,7 +499,7 @@ impl NetworkProtocolHandler for SyncProtocolHandler { ); } - fn connected(&self, io: &NetworkContext, peer: &PeerId) { + fn connected(&self, io: &dyn NetworkContext, peer: &PeerId) { trace_time!("sync::connected"); // If warp protocol is supported only allow warp handshake let warp_protocol = io @@ -515,7 +515,7 @@ impl NetworkProtocolHandler for SyncProtocolHandler { } } - fn disconnected(&self, io: &NetworkContext, peer: &PeerId) { + fn disconnected(&self, io: &dyn NetworkContext, peer: &PeerId) { trace_time!("sync::disconnected"); if io.subprotocol_name() != WARP_SYNC_PROTOCOL_ID { self.sync.write().on_peer_aborting( @@ -525,7 +525,7 @@ impl NetworkProtocolHandler for SyncProtocolHandler { } } - fn timeout(&self, io: &NetworkContext, timer: TimerToken) { + fn timeout(&self, io: &dyn NetworkContext, timer: TimerToken) { trace_time!("sync::timeout"); let mut io = NetSyncIo::new(io, &*self.chain, &*self.snapshot_service, &self.overlay); match timer { @@ -697,12 +697,12 @@ impl ChainNotify for EthSync { /// PIP event handler. /// Simply queues transactions from light client peers. -struct TxRelay(Arc); +struct TxRelay(Arc); impl LightHandler for TxRelay { fn on_transactions( &self, - ctx: &EventContext, + ctx: &dyn EventContext, relay: &[::types::transaction::UnverifiedTransaction], ) { trace!(target: "pip", "Relaying {} transactions from peer {}", relay.len(), ctx.peer()); @@ -730,7 +730,7 @@ pub trait ManageNetwork: Send + Sync { /// Returns the minimum and maximum peers. fn num_peers_range(&self) -> RangeInclusive; /// Get network context for protocol. - fn with_proto_context(&self, proto: ProtocolId, f: &mut FnMut(&NetworkContext)); + fn with_proto_context(&self, proto: ProtocolId, f: &mut dyn FnMut(&dyn NetworkContext)); } impl ManageNetwork for EthSync { @@ -782,7 +782,7 @@ impl ManageNetwork for EthSync { self.network.num_peers_range() } - fn with_proto_context(&self, proto: ProtocolId, f: &mut FnMut(&NetworkContext)) { + fn with_proto_context(&self, proto: ProtocolId, f: &mut dyn FnMut(&dyn NetworkContext)) { self.network.with_context_eval(proto, f); } } @@ -964,7 +964,7 @@ pub trait LightNetworkDispatcher { /// Execute a closure with a protocol context. fn with_context(&self, f: F) -> Option where - F: FnOnce(&::light::net::BasicContext) -> T; + F: FnOnce(&dyn crate::light::net::BasicContext) -> T; } /// Configuration for the light sync. @@ -978,7 +978,7 @@ pub struct LightSyncParams { /// Subprotocol name. pub subprotocol_name: [u8; 3], /// Other handlers to attach. - pub handlers: Vec>, + pub handlers: Vec>, /// Other subprotocols to run. pub attached_protos: Vec, } @@ -986,7 +986,7 @@ pub struct LightSyncParams { /// Service for light synchronization. pub struct LightSync { proto: Arc, - sync: Arc, + sync: Arc, attached_protos: Vec, network: NetworkService, subprotocol_name: [u8; 3], @@ -1040,7 +1040,7 @@ impl LightSync { } impl ::std::ops::Deref for LightSync { - type Target = ::light_sync::SyncInfo; + type Target = dyn crate::light_sync::SyncInfo; fn deref(&self) -> &Self::Target { &*self.sync @@ -1050,7 +1050,7 @@ impl ::std::ops::Deref for LightSync { impl LightNetworkDispatcher for LightSync { fn with_context(&self, f: F) -> Option where - F: FnOnce(&::light::net::BasicContext) -> T, + F: FnOnce(&dyn crate::light::net::BasicContext) -> T, { self.network .with_context_eval(self.subprotocol_name, move |ctx| { @@ -1119,7 +1119,7 @@ impl ManageNetwork for LightSync { self.network.num_peers_range() } - fn with_proto_context(&self, proto: ProtocolId, f: &mut FnMut(&NetworkContext)) { + fn with_proto_context(&self, proto: ProtocolId, f: &mut dyn FnMut(&dyn NetworkContext)) { self.network.with_context_eval(proto, f); } } diff --git a/ethcore/sync/src/block_sync.rs b/ethcore/sync/src/block_sync.rs index 58bd00819..91294ce96 100644 --- a/ethcore/sync/src/block_sync.rs +++ b/ethcore/sync/src/block_sync.rs @@ -231,7 +231,7 @@ impl BlockDownloader { /// Add new block headers. pub fn import_headers( &mut self, - io: &mut SyncIo, + io: &mut dyn SyncIo, r: &Rlp, expected_hash: H256, ) -> Result { @@ -463,7 +463,7 @@ impl BlockDownloader { Ok(()) } - fn start_sync_round(&mut self, io: &mut SyncIo) { + fn start_sync_round(&mut self, io: &mut dyn SyncIo) { self.state = State::ChainHead; trace_sync!( self, @@ -541,7 +541,7 @@ impl BlockDownloader { pub fn request_blocks( &mut self, peer_id: PeerId, - io: &mut SyncIo, + io: &mut dyn SyncIo, num_active_peers: usize, ) -> Option { match self.state { @@ -610,7 +610,11 @@ impl BlockDownloader { /// Checks if there are blocks fully downloaded that can be imported into the blockchain and does the import. /// Returns DownloadAction::Reset if it is imported all the the blocks it can and all downloading peers should be reset - pub fn collect_blocks(&mut self, io: &mut SyncIo, allow_out_of_order: bool) -> DownloadAction { + pub fn collect_blocks( + &mut self, + io: &mut dyn SyncIo, + allow_out_of_order: bool, + ) -> DownloadAction { let mut download_action = DownloadAction::None; let mut imported = HashSet::new(); let blocks = self.blocks.drain(); @@ -748,7 +752,7 @@ mod tests { fn import_headers( headers: &[BlockHeader], downloader: &mut BlockDownloader, - io: &mut SyncIo, + io: &mut dyn SyncIo, ) -> Result { let mut stream = RlpStream::new(); stream.append_list(headers); @@ -761,7 +765,7 @@ mod tests { fn import_headers_ok( headers: &[BlockHeader], downloader: &mut BlockDownloader, - io: &mut SyncIo, + io: &mut dyn SyncIo, ) { let res = import_headers(headers, downloader, io); assert!(res.is_ok()); diff --git a/ethcore/sync/src/blocks.rs b/ethcore/sync/src/blocks.rs index b0ece9250..5297070e5 100644 --- a/ethcore/sync/src/blocks.rs +++ b/ethcore/sync/src/blocks.rs @@ -619,7 +619,7 @@ mod test { client.add_blocks(100, EachBlockWith::Nothing); let hashes = (0..100) .map(|i| { - (&client as &BlockChainClient) + (&client as &dyn BlockChainClient) .block_hash(BlockId::Number(i)) .unwrap() }) @@ -639,7 +639,7 @@ mod test { client.add_blocks(nblocks, EachBlockWith::Nothing); let blocks: Vec<_> = (0..nblocks) .map(|i| { - (&client as &BlockChainClient) + (&client as &dyn BlockChainClient) .block(BlockId::Number(i as BlockNumber)) .unwrap() .into_inner() @@ -719,7 +719,7 @@ mod test { client.add_blocks(nblocks, EachBlockWith::Nothing); let blocks: Vec<_> = (0..nblocks) .map(|i| { - (&client as &BlockChainClient) + (&client as &dyn BlockChainClient) .block(BlockId::Number(i as BlockNumber)) .unwrap() .into_inner() @@ -755,7 +755,7 @@ mod test { client.add_blocks(nblocks, EachBlockWith::Nothing); let blocks: Vec<_> = (0..nblocks) .map(|i| { - (&client as &BlockChainClient) + (&client as &dyn BlockChainClient) .block(BlockId::Number(i as BlockNumber)) .unwrap() .into_inner() diff --git a/ethcore/sync/src/chain/handler.rs b/ethcore/sync/src/chain/handler.rs index 5f230bf0d..08832b7d9 100644 --- a/ethcore/sync/src/chain/handler.rs +++ b/ethcore/sync/src/chain/handler.rs @@ -54,7 +54,7 @@ impl SyncHandler { /// Handle incoming packet from peer pub fn on_packet( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer: PeerId, packet_id: u8, data: &[u8], @@ -102,13 +102,13 @@ impl SyncHandler { } /// Called when peer sends us new consensus packet - pub fn on_consensus_packet(io: &mut SyncIo, peer_id: PeerId, r: &Rlp) { + pub fn on_consensus_packet(io: &mut dyn SyncIo, peer_id: PeerId, r: &Rlp) { trace!(target: "sync", "Received consensus packet from {:?}", peer_id); io.chain().queue_consensus_message(r.as_raw().to_vec()); } /// Called by peer when it is disconnecting - pub fn on_peer_aborting(sync: &mut ChainSync, io: &mut SyncIo, peer_id: PeerId) { + pub fn on_peer_aborting(sync: &mut ChainSync, io: &mut dyn SyncIo, peer_id: PeerId) { trace!(target: "sync", "== Disconnecting {}: {}", peer_id, io.peer_version(peer_id)); sync.handshaking_peers.remove(&peer_id); if sync.peers.contains_key(&peer_id) { @@ -139,7 +139,7 @@ impl SyncHandler { } /// Called when a new peer is connected - pub fn on_peer_connected(sync: &mut ChainSync, io: &mut SyncIo, peer: PeerId) { + pub fn on_peer_connected(sync: &mut ChainSync, io: &mut dyn SyncIo, peer: PeerId) { trace!(target: "sync", "== Connected {}: {}", peer, io.peer_version(peer)); if let Err(e) = sync.send_status(io, peer) { debug!(target:"sync", "Error sending status request: {:?}", e); @@ -152,7 +152,7 @@ impl SyncHandler { /// Called by peer once it has new block bodies pub fn on_peer_new_block( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, r: &Rlp, ) -> Result<(), DownloaderImportError> { @@ -221,7 +221,7 @@ impl SyncHandler { /// Handles `NewHashes` packet. Initiates headers download for any unknown hashes. pub fn on_peer_new_hashes( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, r: &Rlp, ) -> Result<(), DownloaderImportError> { @@ -305,7 +305,7 @@ impl SyncHandler { /// Called by peer once it has new block bodies fn on_peer_block_bodies( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, r: &Rlp, ) -> Result<(), DownloaderImportError> { @@ -360,7 +360,7 @@ impl SyncHandler { fn on_peer_fork_header( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, r: &Rlp, ) -> Result<(), DownloaderImportError> { @@ -404,7 +404,7 @@ impl SyncHandler { /// Called by peer once it has new block headers during sync fn on_peer_block_headers( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, r: &Rlp, ) -> Result<(), DownloaderImportError> { @@ -484,7 +484,7 @@ impl SyncHandler { /// Called by peer once it has new block receipts fn on_peer_block_receipts( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, r: &Rlp, ) -> Result<(), DownloaderImportError> { @@ -539,7 +539,7 @@ impl SyncHandler { /// Called when snapshot manifest is downloaded from a peer. fn on_snapshot_manifest( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, r: &Rlp, ) -> Result<(), DownloaderImportError> { @@ -580,7 +580,7 @@ impl SyncHandler { /// Called when snapshot data is downloaded from a peer. fn on_snapshot_data( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, r: &Rlp, ) -> Result<(), DownloaderImportError> { @@ -653,7 +653,7 @@ impl SyncHandler { /// Called by peer to report status fn on_peer_status( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, r: &Rlp, ) -> Result<(), DownloaderImportError> { @@ -768,7 +768,7 @@ impl SyncHandler { /// Called when peer sends us new transactions pub fn on_peer_transactions( sync: &ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, r: &Rlp, ) -> Result<(), PacketDecodeError> { @@ -799,7 +799,7 @@ impl SyncHandler { /// Called when peer sends us signed private transaction packet fn on_signed_private_transaction( sync: &mut ChainSync, - _io: &mut SyncIo, + _io: &mut dyn SyncIo, peer_id: PeerId, r: &Rlp, ) -> Result<(), DownloaderImportError> { @@ -832,7 +832,7 @@ impl SyncHandler { /// Called when peer sends us new private transaction packet fn on_private_transaction( sync: &mut ChainSync, - _io: &mut SyncIo, + _io: &mut dyn SyncIo, peer_id: PeerId, r: &Rlp, ) -> Result<(), DownloaderImportError> { diff --git a/ethcore/sync/src/chain/mod.rs b/ethcore/sync/src/chain/mod.rs index fc114b51a..a374b279b 100644 --- a/ethcore/sync/src/chain/mod.rs +++ b/ethcore/sync/src/chain/mod.rs @@ -392,8 +392,8 @@ impl ChainSyncApi { /// Creates new `ChainSyncApi` pub fn new( config: SyncConfig, - chain: &BlockChainClient, - private_tx_handler: Option>, + chain: &dyn BlockChainClient, + private_tx_handler: Option>, priority_tasks: mpsc::Receiver, ) -> Self { ChainSyncApi { @@ -429,7 +429,7 @@ impl ChainSyncApi { } /// Dispatch incoming requests and responses - pub fn dispatch_packet(&self, io: &mut SyncIo, peer: PeerId, packet_id: u8, data: &[u8]) { + pub fn dispatch_packet(&self, io: &mut dyn SyncIo, peer: PeerId, packet_id: u8, data: &[u8]) { SyncSupplier::dispatch_packet(&self.sync, io, peer, packet_id, data) } @@ -439,7 +439,7 @@ impl ChainSyncApi { /// /// NOTE This method should only handle stuff that can be canceled and would reach other peers /// by other means. - pub fn process_priority_queue(&self, io: &mut SyncIo) { + pub fn process_priority_queue(&self, io: &mut dyn SyncIo) { fn check_deadline(deadline: Instant) -> Option { let now = Instant::now(); if now > deadline { @@ -516,7 +516,11 @@ impl ChainSyncApi { // Static methods impl ChainSync { /// creates rlp to send for the tree defined by 'from' and 'to' hashes - fn create_new_hashes_rlp(chain: &BlockChainClient, from: &H256, to: &H256) -> Option { + fn create_new_hashes_rlp( + chain: &dyn BlockChainClient, + from: &H256, + to: &H256, + ) -> Option { match chain.tree_route(from, to) { Some(route) => { let uncles = chain.find_uncles(from).unwrap_or_else(Vec::new); @@ -551,7 +555,7 @@ impl ChainSync { } /// creates latest block rlp for the given client - fn create_latest_block_rlp(chain: &BlockChainClient) -> Bytes { + fn create_latest_block_rlp(chain: &dyn BlockChainClient) -> Bytes { Self::create_block_rlp( &chain .block(BlockId::Hash(chain.chain_info().best_block_hash)) @@ -562,7 +566,7 @@ impl ChainSync { } /// creates given hash block rlp for the given client - fn create_new_block_rlp(chain: &BlockChainClient, hash: &H256) -> Bytes { + fn create_new_block_rlp(chain: &dyn BlockChainClient, hash: &H256) -> Bytes { Self::create_block_rlp( &chain .block(BlockId::Hash(hash.clone())) @@ -585,7 +589,7 @@ impl ChainSync { peers } - fn get_init_state(warp_sync: WarpSync, chain: &BlockChainClient) -> SyncState { + fn get_init_state(warp_sync: WarpSync, chain: &dyn BlockChainClient) -> SyncState { let best_block = chain.chain_info().best_block_number; match warp_sync { WarpSync::Enabled => SyncState::WaitingPeers, @@ -638,7 +642,7 @@ pub struct ChainSync { /// Enable ancient block downloading download_old_blocks: bool, /// Shared private tx service. - private_tx_handler: Option>, + private_tx_handler: Option>, /// Enable warp sync. warp_sync: WarpSync, } @@ -647,8 +651,8 @@ impl ChainSync { /// Create a new instance of syncing strategy. pub fn new( config: SyncConfig, - chain: &BlockChainClient, - private_tx_handler: Option>, + chain: &dyn BlockChainClient, + private_tx_handler: Option>, ) -> Self { let chain_info = chain.chain_info(); let best_block = chain.chain_info().best_block_number; @@ -744,14 +748,14 @@ impl ChainSync { } /// Abort all sync activity - pub fn abort(&mut self, io: &mut SyncIo) { + pub fn abort(&mut self, io: &mut dyn SyncIo) { self.reset_and_continue(io); self.peers.clear(); } /// Reset sync. Clear all downloaded data but keep the queue. /// Set sync state to the given state or to the initial state if `None` is provided. - fn reset(&mut self, io: &mut SyncIo, state: Option) { + fn reset(&mut self, io: &mut dyn SyncIo, state: Option) { self.new_blocks.reset(); let chain_info = io.chain().chain_info(); for (_, ref mut p) in &mut self.peers { @@ -770,7 +774,7 @@ impl ChainSync { } /// Restart sync - pub fn reset_and_continue(&mut self, io: &mut SyncIo) { + pub fn reset_and_continue(&mut self, io: &mut dyn SyncIo) { trace!(target: "sync", "Restarting"); if self.state == SyncState::SnapshotData { debug!(target:"sync", "Aborting snapshot restore"); @@ -783,12 +787,12 @@ impl ChainSync { /// Remove peer from active peer set. Peer will be reactivated on the next sync /// round. - fn deactivate_peer(&mut self, _io: &mut SyncIo, peer_id: PeerId) { + fn deactivate_peer(&mut self, _io: &mut dyn SyncIo, peer_id: PeerId) { trace!(target: "sync", "Deactivating peer {}", peer_id); self.active_peers.remove(&peer_id); } - fn maybe_start_snapshot_sync(&mut self, io: &mut SyncIo) { + fn maybe_start_snapshot_sync(&mut self, io: &mut dyn SyncIo) { if !self.warp_sync.is_enabled() || io.snapshot_service().supported_versions().is_none() { trace!(target: "sync", "Skipping warp sync. Disabled or not supported."); return; @@ -868,7 +872,7 @@ impl ChainSync { } } - fn start_snapshot_sync(&mut self, io: &mut SyncIo, peers: &[PeerId]) { + fn start_snapshot_sync(&mut self, io: &mut dyn SyncIo, peers: &[PeerId]) { if !self.snapshot.have_manifest() { for p in peers { if self @@ -888,13 +892,13 @@ impl ChainSync { } /// Restart sync disregarding the block queue status. May end up re-downloading up to QUEUE_SIZE blocks - pub fn restart(&mut self, io: &mut SyncIo) { + pub fn restart(&mut self, io: &mut dyn SyncIo) { self.update_targets(io.chain()); self.reset_and_continue(io); } /// Update sync after the blockchain has been changed externally. - pub fn update_targets(&mut self, chain: &BlockChainClient) { + pub fn update_targets(&mut self, chain: &dyn BlockChainClient) { // Do not assume that the block queue/chain still has our last_imported_block let chain = chain.chain_info(); self.new_blocks = BlockDownloader::new( @@ -923,7 +927,7 @@ impl ChainSync { } /// Resume downloading - pub fn continue_sync(&mut self, io: &mut SyncIo) { + pub fn continue_sync(&mut self, io: &mut dyn SyncIo) { if self.state == SyncState::Waiting { trace!(target: "sync", "Waiting for the block queue"); } else if self.state == SyncState::SnapshotWaiting { @@ -974,7 +978,7 @@ impl ChainSync { } /// Called after all blocks have been downloaded - fn complete_sync(&mut self, io: &mut SyncIo) { + fn complete_sync(&mut self, io: &mut dyn SyncIo) { trace!(target: "sync", "Sync complete"); self.reset(io, Some(SyncState::Idle)); } @@ -986,7 +990,7 @@ impl ChainSync { } /// Find something to do for a peer. Called for a new peer or when a peer is done with its task. - fn sync_peer(&mut self, io: &mut SyncIo, peer_id: PeerId, force: bool) { + fn sync_peer(&mut self, io: &mut dyn SyncIo, peer_id: PeerId, force: bool) { if !self.active_peers.contains(&peer_id) { trace!(target: "sync", "Skipping deactivated peer {}", peer_id); return; @@ -1136,7 +1140,7 @@ impl ChainSync { } /// Checks if there are blocks fully downloaded that can be imported into the blockchain and does the import. - fn collect_blocks(&mut self, io: &mut SyncIo, block_set: BlockSet) { + fn collect_blocks(&mut self, io: &mut dyn SyncIo, block_set: BlockSet) { match block_set { BlockSet::NewBlocks => { if self @@ -1201,7 +1205,7 @@ impl ChainSync { } /// Send Status message - fn send_status(&mut self, io: &mut SyncIo, peer: PeerId) -> Result<(), network::Error> { + fn send_status(&mut self, io: &mut dyn SyncIo, peer: PeerId) -> Result<(), network::Error> { let warp_protocol_version = io.protocol_version(&WARP_SYNC_PROTOCOL_ID, peer); let warp_protocol = warp_protocol_version != 0; let private_tx_protocol = warp_protocol_version >= PAR_PROTOCOL_VERSION_3.0; @@ -1233,7 +1237,7 @@ impl ChainSync { io.respond(StatusPacket.id(), packet.out()) } - pub fn maintain_peers(&mut self, io: &mut SyncIo) { + pub fn maintain_peers(&mut self, io: &mut dyn SyncIo) { let tick = Instant::now(); let mut aborting = Vec::new(); for (peer_id, peer) in &self.peers { @@ -1267,7 +1271,7 @@ impl ChainSync { } } - fn check_resume(&mut self, io: &mut SyncIo) { + fn check_resume(&mut self, io: &mut dyn SyncIo) { match self.state { SyncState::Waiting if !io.chain().queue_info().is_full() => { self.state = SyncState::Blocks; @@ -1369,7 +1373,7 @@ impl ChainSync { } /// Maintain other peers. Send out any new blocks and transactions - pub fn maintain_sync(&mut self, io: &mut SyncIo) { + pub fn maintain_sync(&mut self, io: &mut dyn SyncIo) { self.maybe_start_snapshot_sync(io); self.check_resume(io); } @@ -1377,7 +1381,7 @@ impl ChainSync { /// called when block is imported to chain - propagates the blocks and updates transactions sent to peers pub fn chain_new_blocks( &mut self, - io: &mut SyncIo, + io: &mut dyn SyncIo, _imported: &[H256], invalid: &[H256], enacted: &[H256], @@ -1409,22 +1413,22 @@ impl ChainSync { } } - pub fn on_packet(&mut self, io: &mut SyncIo, peer: PeerId, packet_id: u8, data: &[u8]) { + pub fn on_packet(&mut self, io: &mut dyn SyncIo, peer: PeerId, packet_id: u8, data: &[u8]) { SyncHandler::on_packet(self, io, peer, packet_id, data); } /// Called by peer when it is disconnecting - pub fn on_peer_aborting(&mut self, io: &mut SyncIo, peer: PeerId) { + pub fn on_peer_aborting(&mut self, io: &mut dyn SyncIo, peer: PeerId) { SyncHandler::on_peer_aborting(self, io, peer); } /// Called when a new peer is connected - pub fn on_peer_connected(&mut self, io: &mut SyncIo, peer: PeerId) { + pub fn on_peer_connected(&mut self, io: &mut dyn SyncIo, peer: PeerId) { SyncHandler::on_peer_connected(self, io, peer); } /// propagates new transactions to all peers - pub fn propagate_new_transactions(&mut self, io: &mut SyncIo) { + pub fn propagate_new_transactions(&mut self, io: &mut dyn SyncIo) { let deadline = Instant::now() + Duration::from_millis(500); SyncPropagator::propagate_new_transactions(self, io, || { if deadline > Instant::now() { @@ -1437,14 +1441,14 @@ impl ChainSync { } /// Broadcast consensus message to peers. - pub fn propagate_consensus_packet(&mut self, io: &mut SyncIo, packet: Bytes) { + pub fn propagate_consensus_packet(&mut self, io: &mut dyn SyncIo, packet: Bytes) { SyncPropagator::propagate_consensus_packet(self, io, packet); } /// Broadcast private transaction message to peers. pub fn propagate_private_transaction( &mut self, - io: &mut SyncIo, + io: &mut dyn SyncIo, transaction_hash: H256, packet_id: SyncPacket, packet: Bytes, @@ -1558,7 +1562,10 @@ pub mod tests { assert!(!sync_status(SyncState::Idle).is_syncing(queue_info(0, 0))); } - pub fn dummy_sync_with_peer(peer_latest_hash: H256, client: &BlockChainClient) -> ChainSync { + pub fn dummy_sync_with_peer( + peer_latest_hash: H256, + client: &dyn BlockChainClient, + ) -> ChainSync { let mut sync = ChainSync::new(SyncConfig::default(), client, None); insert_dummy_peer(&mut sync, 0, peer_latest_hash); sync diff --git a/ethcore/sync/src/chain/propagator.rs b/ethcore/sync/src/chain/propagator.rs index c893c6f90..c0d92d950 100644 --- a/ethcore/sync/src/chain/propagator.rs +++ b/ethcore/sync/src/chain/propagator.rs @@ -43,13 +43,13 @@ impl SyncPropagator { pub fn propagate_blocks( sync: &mut ChainSync, chain_info: &BlockChainInfo, - io: &mut SyncIo, + io: &mut dyn SyncIo, blocks: &[H256], peers: &[PeerId], ) -> usize { trace!(target: "sync", "Sending NewBlocks to {:?}", peers); let sent = peers.len(); - let mut send_packet = |io: &mut SyncIo, rlp: Bytes| { + let mut send_packet = |io: &mut dyn SyncIo, rlp: Bytes| { for peer_id in peers { SyncPropagator::send_packet(io, *peer_id, NewBlockPacket, rlp.clone()); @@ -76,7 +76,7 @@ impl SyncPropagator { pub fn propagate_new_hashes( sync: &mut ChainSync, chain_info: &BlockChainInfo, - io: &mut SyncIo, + io: &mut dyn SyncIo, peers: &[PeerId], ) -> usize { trace!(target: "sync", "Sending NewHashes to {:?}", peers); @@ -101,7 +101,7 @@ impl SyncPropagator { /// propagates new transactions to all peers pub fn propagate_new_transactions bool>( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, mut should_continue: F, ) -> usize { // Early out if nobody to send to. @@ -159,7 +159,7 @@ impl SyncPropagator { fn propagate_transactions_to_peers bool>( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peers: Vec, transactions: Vec<&SignedTransaction>, mut should_continue: F, @@ -179,7 +179,7 @@ impl SyncPropagator { // Clear old transactions from stats sync.transactions_stats.retain(&all_transactions_hashes); - let send_packet = |io: &mut SyncIo, peer_id: PeerId, sent: usize, rlp: Bytes| { + let send_packet = |io: &mut dyn SyncIo, peer_id: PeerId, sent: usize, rlp: Bytes| { let size = rlp.len(); SyncPropagator::send_packet(io, peer_id, TransactionsPacket, rlp); trace!(target: "sync", "{:02} <- Transactions ({} entries; {} bytes)", peer_id, sent, size); @@ -279,7 +279,7 @@ impl SyncPropagator { sent_to_peers } - pub fn propagate_latest_blocks(sync: &mut ChainSync, io: &mut SyncIo, sealed: &[H256]) { + pub fn propagate_latest_blocks(sync: &mut ChainSync, io: &mut dyn SyncIo, sealed: &[H256]) { let chain_info = io.chain().chain_info(); if (((chain_info.best_block_number as i64) - (sync.last_sent_block_number as i64)).abs() as BlockNumber) @@ -304,7 +304,11 @@ impl SyncPropagator { } /// Distribute valid proposed blocks to subset of current peers. - pub fn propagate_proposed_blocks(sync: &mut ChainSync, io: &mut SyncIo, proposed: &[Bytes]) { + pub fn propagate_proposed_blocks( + sync: &mut ChainSync, + io: &mut dyn SyncIo, + proposed: &[Bytes], + ) { let peers = sync.get_consensus_peers(); trace!(target: "sync", "Sending proposed blocks to {:?}", peers); for block in proposed { @@ -316,7 +320,7 @@ impl SyncPropagator { } /// Broadcast consensus message to peers. - pub fn propagate_consensus_packet(sync: &mut ChainSync, io: &mut SyncIo, packet: Bytes) { + pub fn propagate_consensus_packet(sync: &mut ChainSync, io: &mut dyn SyncIo, packet: Bytes) { let lucky_peers = ChainSync::select_random_peers(&sync.get_consensus_peers()); trace!(target: "sync", "Sending consensus packet to {:?}", lucky_peers); for peer_id in lucky_peers { @@ -327,7 +331,7 @@ impl SyncPropagator { /// Broadcast private transaction message to peers. pub fn propagate_private_transaction( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, transaction_hash: H256, packet_id: SyncPacket, packet: Bytes, @@ -367,7 +371,12 @@ impl SyncPropagator { } /// Generic packet sender - pub fn send_packet(sync: &mut SyncIo, peer_id: PeerId, packet_id: SyncPacket, packet: Bytes) { + pub fn send_packet( + sync: &mut dyn SyncIo, + peer_id: PeerId, + packet_id: SyncPacket, + packet: Bytes, + ) { if let Err(e) = sync.send(peer_id, packet_id, packet) { debug!(target:"sync", "Error sending packet: {:?}", e); sync.disconnect_peer(peer_id); diff --git a/ethcore/sync/src/chain/requester.rs b/ethcore/sync/src/chain/requester.rs index 287ff61b5..288fbb34a 100644 --- a/ethcore/sync/src/chain/requester.rs +++ b/ethcore/sync/src/chain/requester.rs @@ -40,7 +40,7 @@ impl SyncRequester { /// Perform block download request` pub fn request_blocks( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, request: BlockRequest, block_set: BlockSet, @@ -63,7 +63,7 @@ impl SyncRequester { /// Request block bodies from a peer fn request_bodies( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, hashes: Vec, set: BlockSet, @@ -89,7 +89,7 @@ impl SyncRequester { /// Request headers from a peer by block number pub fn request_fork_header( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, n: BlockNumber, ) { @@ -110,7 +110,7 @@ impl SyncRequester { } /// Find some headers or blocks to download for a peer. - pub fn request_snapshot_data(sync: &mut ChainSync, io: &mut SyncIo, peer_id: PeerId) { + pub fn request_snapshot_data(sync: &mut ChainSync, io: &mut dyn SyncIo, peer_id: PeerId) { // find chunk data to download if let Some(hash) = sync.snapshot.needed_chunk() { if let Some(ref mut peer) = sync.peers.get_mut(&peer_id) { @@ -121,7 +121,7 @@ impl SyncRequester { } /// Request snapshot manifest from a peer. - pub fn request_snapshot_manifest(sync: &mut ChainSync, io: &mut SyncIo, peer_id: PeerId) { + pub fn request_snapshot_manifest(sync: &mut ChainSync, io: &mut dyn SyncIo, peer_id: PeerId) { trace!(target: "sync", "{} <- GetSnapshotManifest", peer_id); let rlp = RlpStream::new_list(0); SyncRequester::send_request( @@ -137,7 +137,7 @@ impl SyncRequester { /// Request headers from a peer by block hash fn request_headers_by_hash( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, h: &H256, count: u64, @@ -167,7 +167,7 @@ impl SyncRequester { /// Request block receipts from a peer fn request_receipts( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, hashes: Vec, set: BlockSet, @@ -193,7 +193,7 @@ impl SyncRequester { /// Request snapshot chunk from a peer. fn request_snapshot_chunk( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, chunk: &H256, ) { @@ -213,7 +213,7 @@ impl SyncRequester { /// Generic request sender fn send_request( sync: &mut ChainSync, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer_id: PeerId, asking: PeerAsking, packet_id: SyncPacket, diff --git a/ethcore/sync/src/chain/supplier.rs b/ethcore/sync/src/chain/supplier.rs index a97678268..76cf6b309 100644 --- a/ethcore/sync/src/chain/supplier.rs +++ b/ethcore/sync/src/chain/supplier.rs @@ -49,7 +49,7 @@ impl SyncSupplier { // to chain sync from the outside world. pub fn dispatch_packet( sync: &RwLock, - io: &mut SyncIo, + io: &mut dyn SyncIo, peer: PeerId, packet_id: u8, data: &[u8], @@ -143,7 +143,7 @@ impl SyncSupplier { } /// Respond to GetBlockHeaders request - fn return_block_headers(io: &SyncIo, r: &Rlp, peer_id: PeerId) -> RlpResponseResult { + fn return_block_headers(io: &dyn SyncIo, r: &Rlp, peer_id: PeerId) -> RlpResponseResult { let payload_soft_limit = io.payload_soft_limit(); // Packet layout: // [ block: { P , B_32 }, maxHeaders: P, skip: P, reverse: P in { 0 , 1 } ] @@ -226,7 +226,7 @@ impl SyncSupplier { } /// Respond to GetBlockBodies request - fn return_block_bodies(io: &SyncIo, r: &Rlp, peer_id: PeerId) -> RlpResponseResult { + fn return_block_bodies(io: &dyn SyncIo, r: &Rlp, peer_id: PeerId) -> RlpResponseResult { let payload_soft_limit = io.payload_soft_limit(); let mut count = r.item_count().unwrap_or(0); if count == 0 { @@ -253,7 +253,7 @@ impl SyncSupplier { } /// Respond to GetNodeData request - fn return_node_data(io: &SyncIo, r: &Rlp, peer_id: PeerId) -> RlpResponseResult { + fn return_node_data(io: &dyn SyncIo, r: &Rlp, peer_id: PeerId) -> RlpResponseResult { let payload_soft_limit = io.payload_soft_limit(); let mut count = r.item_count().unwrap_or(0); trace!(target: "sync", "{} -> GetNodeData: {} entries", peer_id, count); @@ -284,7 +284,7 @@ impl SyncSupplier { Ok(Some((NodeDataPacket.id(), rlp))) } - fn return_receipts(io: &SyncIo, rlp: &Rlp, peer_id: PeerId) -> RlpResponseResult { + fn return_receipts(io: &dyn SyncIo, rlp: &Rlp, peer_id: PeerId) -> RlpResponseResult { let payload_soft_limit = io.payload_soft_limit(); let mut count = rlp.item_count().unwrap_or(0); trace!(target: "sync", "{} -> GetReceipts: {} entries", peer_id, count); @@ -313,7 +313,7 @@ impl SyncSupplier { } /// Respond to GetSnapshotManifest request - fn return_snapshot_manifest(io: &SyncIo, r: &Rlp, peer_id: PeerId) -> RlpResponseResult { + fn return_snapshot_manifest(io: &dyn SyncIo, r: &Rlp, peer_id: PeerId) -> RlpResponseResult { let count = r.item_count().unwrap_or(0); trace!(target: "warp", "{} -> GetSnapshotManifest", peer_id); if count != 0 { @@ -336,7 +336,7 @@ impl SyncSupplier { } /// Respond to GetSnapshotData request - fn return_snapshot_data(io: &SyncIo, r: &Rlp, peer_id: PeerId) -> RlpResponseResult { + fn return_snapshot_data(io: &dyn SyncIo, r: &Rlp, peer_id: PeerId) -> RlpResponseResult { let hash: H256 = r.val_at(0)?; trace!(target: "warp", "{} -> GetSnapshotData {:?}", peer_id, hash); let rlp = match io.snapshot_service().chunk(hash) { @@ -355,14 +355,14 @@ impl SyncSupplier { } fn return_rlp( - io: &mut SyncIo, + io: &mut dyn SyncIo, rlp: &Rlp, peer: PeerId, rlp_func: FRlp, error_func: FError, ) -> Result<(), PacketDecodeError> where - FRlp: Fn(&SyncIo, &Rlp, PeerId) -> RlpResponseResult, + FRlp: Fn(&dyn SyncIo, &Rlp, PeerId) -> RlpResponseResult, FError: FnOnce(network::Error) -> String, { let response = rlp_func(io, rlp, peer); @@ -420,7 +420,7 @@ mod test { client.add_blocks(100, EachBlockWith::Nothing); let blocks: Vec<_> = (0..100) .map(|i| { - (&client as &BlockChainClient) + (&client as &dyn BlockChainClient) .block(BlockId::Number(i as BlockNumber)) .map(|b| b.into_inner()) .unwrap() diff --git a/ethcore/sync/src/light_sync/mod.rs b/ethcore/sync/src/light_sync/mod.rs index 00cb0f0d4..7c47e75fa 100644 --- a/ethcore/sync/src/light_sync/mod.rs +++ b/ethcore/sync/src/light_sync/mod.rs @@ -118,7 +118,7 @@ impl AncestorSearch { } } - fn process_response(self, ctx: &ResponseContext, client: &L) -> AncestorSearch + fn process_response(self, ctx: &dyn ResponseContext, client: &L) -> AncestorSearch where L: AsLightClient, { @@ -261,7 +261,7 @@ impl Deref for SyncStateWrapper { struct ResponseCtx<'a> { peer: PeerId, req_id: ReqId, - ctx: &'a BasicContext, + ctx: &'a dyn BasicContext, data: &'a [encoded::Header], } @@ -302,7 +302,7 @@ struct PendingReq { impl Handler for LightSync { fn on_connect( &self, - ctx: &EventContext, + ctx: &dyn EventContext, status: &Status, capabilities: &Capabilities, ) -> PeerStatus { @@ -331,7 +331,7 @@ impl Handler for LightSync { } } - fn on_disconnect(&self, ctx: &EventContext, unfulfilled: &[ReqId]) { + fn on_disconnect(&self, ctx: &dyn EventContext, unfulfilled: &[ReqId]) { let peer_id = ctx.peer(); let peer = match self.peers.write().remove(&peer_id).map(|p| p.into_inner()) { @@ -389,7 +389,7 @@ impl Handler for LightSync { self.maintain_sync(ctx.as_basic()); } - fn on_announcement(&self, ctx: &EventContext, announcement: &Announcement) { + fn on_announcement(&self, ctx: &dyn EventContext, announcement: &Announcement) { let (last_td, chain_info) = { let peers = self.peers.read(); match peers.get(&ctx.peer()) { @@ -425,7 +425,7 @@ impl Handler for LightSync { self.maintain_sync(ctx.as_basic()); } - fn on_responses(&self, ctx: &EventContext, req_id: ReqId, responses: &[request::Response]) { + fn on_responses(&self, ctx: &dyn EventContext, req_id: ReqId, responses: &[request::Response]) { let peer = ctx.peer(); if !self.peers.read().contains_key(&peer) { return; @@ -469,7 +469,7 @@ impl Handler for LightSync { self.maintain_sync(ctx.as_basic()); } - fn tick(&self, ctx: &BasicContext) { + fn tick(&self, ctx: &dyn BasicContext) { self.maintain_sync(ctx); } } @@ -502,7 +502,7 @@ impl LightSync { } // handles request dispatch, block import, state machine transitions, and timeouts. - fn maintain_sync(&self, ctx: &BasicContext) { + fn maintain_sync(&self, ctx: &dyn BasicContext) { use ethcore::error::{ Error as EthcoreError, ErrorKind as EthcoreErrorKind, ImportErrorKind, }; diff --git a/ethcore/sync/src/snapshot.rs b/ethcore/sync/src/snapshot.rs index 2643ab615..db9b05996 100644 --- a/ethcore/sync/src/snapshot.rs +++ b/ethcore/sync/src/snapshot.rs @@ -51,7 +51,7 @@ impl Snapshot { } /// Sync the Snapshot completed chunks with the Snapshot Service - pub fn initialize(&mut self, snapshot_service: &SnapshotService) { + pub fn initialize(&mut self, snapshot_service: &dyn SnapshotService) { if self.initialized { return; } diff --git a/ethcore/sync/src/sync_io.rs b/ethcore/sync/src/sync_io.rs index 3ee153694..be826649a 100644 --- a/ethcore/sync/src/sync_io.rs +++ b/ethcore/sync/src/sync_io.rs @@ -37,9 +37,9 @@ pub trait SyncIo { /// Send a packet to a peer using specified protocol. fn send(&mut self, peer_id: PeerId, packet_id: SyncPacket, data: Vec) -> Result<(), Error>; /// Get the blockchain - fn chain(&self) -> &BlockChainClient; + fn chain(&self) -> &dyn BlockChainClient; /// Get the snapshot service. - fn snapshot_service(&self) -> &SnapshotService; + fn snapshot_service(&self) -> &dyn SnapshotService; /// Returns peer version identifier fn peer_version(&self, peer_id: PeerId) -> ClientVersion { ClientVersion::from(peer_id.to_string()) @@ -64,18 +64,18 @@ pub trait SyncIo { /// Wraps `NetworkContext` and the blockchain client pub struct NetSyncIo<'s> { - network: &'s NetworkContext, - chain: &'s BlockChainClient, - snapshot_service: &'s SnapshotService, + network: &'s dyn NetworkContext, + chain: &'s dyn BlockChainClient, + snapshot_service: &'s dyn SnapshotService, chain_overlay: &'s RwLock>, } impl<'s> NetSyncIo<'s> { /// Creates a new instance from the `NetworkContext` and the blockchain client reference. pub fn new( - network: &'s NetworkContext, - chain: &'s BlockChainClient, - snapshot_service: &'s SnapshotService, + network: &'s dyn NetworkContext, + chain: &'s dyn BlockChainClient, + snapshot_service: &'s dyn SnapshotService, chain_overlay: &'s RwLock>, ) -> NetSyncIo<'s> { NetSyncIo { @@ -105,7 +105,7 @@ impl<'s> SyncIo for NetSyncIo<'s> { .send_protocol(packet_id.protocol(), peer_id, packet_id.id(), data) } - fn chain(&self) -> &BlockChainClient { + fn chain(&self) -> &dyn BlockChainClient { self.chain } @@ -113,7 +113,7 @@ impl<'s> SyncIo for NetSyncIo<'s> { self.chain_overlay } - fn snapshot_service(&self) -> &SnapshotService { + fn snapshot_service(&self) -> &dyn SnapshotService { self.snapshot_service } diff --git a/ethcore/sync/src/tests/consensus.rs b/ethcore/sync/src/tests/consensus.rs index 51f66b0e2..0327acd06 100644 --- a/ethcore/sync/src/tests/consensus.rs +++ b/ethcore/sync/src/tests/consensus.rs @@ -49,9 +49,9 @@ fn authority_round() { let chain_id = Spec::new_test_round().chain_id(); let mut net = TestNet::with_spec(2, SyncConfig::default(), Spec::new_test_round); - let io_handler0: Arc> = + let io_handler0: Arc> = Arc::new(TestIoHandler::new(net.peer(0).chain.clone())); - let io_handler1: Arc> = + let io_handler1: Arc> = Arc::new(TestIoHandler::new(net.peer(1).chain.clone())); // Push transaction to both clients. Only one of them gets lucky to produce a block. net.peer(0) diff --git a/ethcore/sync/src/tests/helpers.rs b/ethcore/sync/src/tests/helpers.rs index 952a2c6c0..09bdeee3b 100644 --- a/ethcore/sync/src/tests/helpers.rs +++ b/ethcore/sync/src/tests/helpers.rs @@ -149,7 +149,7 @@ where Ok(()) } - fn chain(&self) -> &BlockChainClient { + fn chain(&self) -> &dyn BlockChainClient { &*self.chain } @@ -163,7 +163,7 @@ where ClientVersion::from(client_id) } - fn snapshot_service(&self) -> &SnapshotService { + fn snapshot_service(&self) -> &dyn SnapshotService { self.snapshot_service } diff --git a/ethcore/sync/src/tests/private.rs b/ethcore/sync/src/tests/private.rs index 790c78dbf..29d5d959b 100644 --- a/ethcore/sync/src/tests/private.rs +++ b/ethcore/sync/src/tests/private.rs @@ -58,9 +58,9 @@ fn send_private_transaction() { let mut net = TestNet::with_spec(2, SyncConfig::default(), seal_spec); let client0 = net.peer(0).chain.clone(); let client1 = net.peer(1).chain.clone(); - let io_handler0: Arc> = + let io_handler0: Arc> = Arc::new(TestIoHandler::new(net.peer(0).chain.clone())); - let io_handler1: Arc> = + let io_handler1: Arc> = Arc::new(TestIoHandler::new(net.peer(1).chain.clone())); net.peer(0) diff --git a/ethcore/vm/src/error.rs b/ethcore/vm/src/error.rs index 552d38288..1d765cb62 100644 --- a/ethcore/vm/src/error.rs +++ b/ethcore/vm/src/error.rs @@ -130,5 +130,5 @@ impl fmt::Display for Error { pub type Result = ::std::result::Result; pub type TrapResult = ::std::result::Result, TrapError>; -pub type ExecTrapResult = TrapResult, Box>; -pub type ExecTrapError = TrapError, Box>; +pub type ExecTrapResult = TrapResult, Box>; +pub type ExecTrapError = TrapError, Box>; diff --git a/ethcore/vm/src/lib.rs b/ethcore/vm/src/lib.rs index f0e13def5..22d2a61ec 100644 --- a/ethcore/vm/src/lib.rs +++ b/ethcore/vm/src/lib.rs @@ -46,17 +46,17 @@ pub trait Exec: Send { /// This function should be used to execute transaction. /// It returns either an error, a known amount of gas left, or parameters to be used /// to compute the final gas left. - fn exec(self: Box, ext: &mut Ext) -> ExecTrapResult; + fn exec(self: Box, ext: &mut dyn Ext) -> ExecTrapResult; } /// Resume call interface pub trait ResumeCall: Send { /// Resume an execution for call, returns back the Vm interface. - fn resume_call(self: Box, result: MessageCallResult) -> Box; + fn resume_call(self: Box, result: MessageCallResult) -> Box; } /// Resume create interface pub trait ResumeCreate: Send { /// Resume an execution from create, returns back the Vm interface. - fn resume_create(self: Box, result: ContractCreateResult) -> Box; + fn resume_create(self: Box, result: ContractCreateResult) -> Box; } diff --git a/ethcore/wasm/run/src/runner.rs b/ethcore/wasm/run/src/runner.rs index edab0732c..c6428ff73 100644 --- a/ethcore/wasm/run/src/runner.rs +++ b/ethcore/wasm/run/src/runner.rs @@ -136,7 +136,7 @@ impl fmt::Display for Fail { } pub fn construct( - ext: &mut vm::Ext, + ext: &mut dyn vm::Ext, source: Vec, arguments: Vec, sender: H160, diff --git a/ethcore/wasm/src/lib.rs b/ethcore/wasm/src/lib.rs index 9efb16c96..611dc667f 100644 --- a/ethcore/wasm/src/lib.rs +++ b/ethcore/wasm/src/lib.rs @@ -96,7 +96,7 @@ enum ExecutionOutcome { } impl WasmInterpreter { - pub fn run(self: Box, ext: &mut vm::Ext) -> vm::Result { + pub fn run(self: Box, ext: &mut dyn vm::Ext) -> vm::Result { let (module, data) = parser::payload(&self.params, ext.schedule().wasm())?; let loaded_module = @@ -204,7 +204,7 @@ impl WasmInterpreter { } impl vm::Exec for WasmInterpreter { - fn exec(self: Box, ext: &mut vm::Ext) -> vm::ExecTrapResult { + fn exec(self: Box, ext: &mut dyn vm::Ext) -> vm::ExecTrapResult { Ok(self.run(ext)) } } diff --git a/ethcore/wasm/src/runtime.rs b/ethcore/wasm/src/runtime.rs index 1ea7f6eee..d4b76b72f 100644 --- a/ethcore/wasm/src/runtime.rs +++ b/ethcore/wasm/src/runtime.rs @@ -33,7 +33,7 @@ pub struct RuntimeContext { pub struct Runtime<'a> { gas_counter: u64, gas_limit: u64, - ext: &'a mut vm::Ext, + ext: &'a mut dyn vm::Ext, context: RuntimeContext, memory: MemoryRef, args: Vec, @@ -149,7 +149,7 @@ type Result = ::std::result::Result; impl<'a> Runtime<'a> { /// New runtime for wasm contract with specified params pub fn with_params( - ext: &mut vm::Ext, + ext: &mut dyn vm::Ext, memory: MemoryRef, gas_limit: u64, args: Vec, diff --git a/miner/local-store/src/lib.rs b/miner/local-store/src/lib.rs index e671cf7d5..6f7d558b4 100644 --- a/miner/local-store/src/lib.rs +++ b/miner/local-store/src/lib.rs @@ -134,7 +134,11 @@ pub trait NodeInfo: Send + Sync { /// Create a new local data store, given a database, a column to write to, and a node. /// Attempts to read data out of the store, and move it into the node. -pub fn create(db: Arc, col: Option, node: T) -> LocalDataStore { +pub fn create( + db: Arc, + col: Option, + node: T, +) -> LocalDataStore { LocalDataStore { db: db, col: col, @@ -147,7 +151,7 @@ pub fn create(db: Arc, col: Option, node: T) -> Lo /// In specific, this will be used to store things like unpropagated local transactions /// and the node security level. pub struct LocalDataStore { - db: Arc, + db: Arc, col: Option, node: T, } diff --git a/miner/src/pool/listener.rs b/miner/src/pool/listener.rs index 7d8b9c86b..d351fc18c 100644 --- a/miner/src/pool/listener.rs +++ b/miner/src/pool/listener.rs @@ -23,7 +23,7 @@ use txpool::{self, VerifiedTransaction}; use pool::VerifiedTransaction as Transaction; -type Listener = Box; +type Listener = Box; /// Manages notifications to pending transaction listeners. #[derive(Default)] diff --git a/miner/src/pool/local_transactions.rs b/miner/src/pool/local_transactions.rs index 3da607dff..980c5aa61 100644 --- a/miner/src/pool/local_transactions.rs +++ b/miner/src/pool/local_transactions.rs @@ -66,7 +66,7 @@ pub struct LocalTransactionsList { max_old: usize, transactions: LinkedHashMap, pending: usize, - in_chain: Option bool + Send + Sync>>, + in_chain: Option bool + Send + Sync>>, } impl fmt::Debug for LocalTransactionsList { diff --git a/miner/src/pool/queue.rs b/miner/src/pool/queue.rs index f5b91b796..f8cdddff9 100644 --- a/miner/src/pool/queue.rs +++ b/miner/src/pool/queue.rs @@ -615,7 +615,7 @@ impl TransactionQueue { } /// Add a callback to be notified about all transactions entering the pool. - pub fn add_listener(&self, f: Box) { + pub fn add_listener(&self, f: Box) { let mut pool = self.pool.write(); (pool.listener_mut().1).0.add(f); } diff --git a/miner/src/pool/replace.rs b/miner/src/pool/replace.rs index 237524cf9..76c169241 100644 --- a/miner/src/pool/replace.rs +++ b/miner/src/pool/replace.rs @@ -136,7 +136,7 @@ mod tests { } fn should_replace( - replace: &ShouldReplace, + replace: &dyn ShouldReplace, old: VerifiedTransaction, new: VerifiedTransaction, ) -> Choice { diff --git a/miner/stratum/src/lib.rs b/miner/stratum/src/lib.rs index 292c7dfa4..df842a1ac 100644 --- a/miner/stratum/src/lib.rs +++ b/miner/stratum/src/lib.rs @@ -74,7 +74,7 @@ pub struct Stratum { impl Stratum { pub fn start( addr: &SocketAddr, - dispatcher: Arc, + dispatcher: Arc, secret: Option, ) -> Result, Error> { let implementation = Arc::new(StratumImpl { @@ -129,7 +129,7 @@ struct StratumImpl { /// List of workers supposed to receive job update job_queue: RwLock>, /// Payload manager - dispatcher: Arc, + dispatcher: Arc, /// Authorized workers (socket - worker_id) workers: Arc>>, /// Secret if any diff --git a/parity-clib/src/lib.rs b/parity-clib/src/lib.rs index cf014e445..0d18bccfa 100644 --- a/parity-clib/src/lib.rs +++ b/parity-clib/src/lib.rs @@ -266,7 +266,11 @@ pub unsafe extern "C" fn parity_set_logger( } // WebSocket event loop -fn parity_ws_worker(client: &RunningClient, query: &str, callback: Arc) -> *const c_void { +fn parity_ws_worker( + client: &RunningClient, + query: &str, + callback: Arc, +) -> *const c_void { let (tx, mut rx) = mpsc::channel(1); let session = Arc::new(PubSubSession::new(tx)); let query_future = client.rpc_query(query, Some(session.clone())); @@ -304,7 +308,7 @@ fn parity_ws_worker(client: &RunningClient, query: &str, callback: Arc fn parity_rpc_worker( client: &RunningClient, query: &str, - callback: Arc, + callback: Arc, timeout_ms: u64, ) { let cb = callback.clone(); diff --git a/parity/account_utils.rs b/parity/account_utils.rs index 90bb778d8..6ca7ec432 100644 --- a/parity/account_utils.rs +++ b/parity/account_utils.rs @@ -63,13 +63,13 @@ mod accounts { pub fn private_tx_signer( _account_provider: Arc, _passwords: &[Password], - ) -> Result, String> { + ) -> Result, String> { Ok(Arc::new(::ethcore_private_tx::DummySigner)) } pub fn accounts_list( _account_provider: Arc, - ) -> Arc Vec
+ Send + Sync> { + ) -> Arc Vec
+ Send + Sync> { Arc::new(|| vec![]) } } @@ -269,7 +269,7 @@ mod accounts { pub fn private_tx_signer( accounts: Arc, passwords: &[Password], - ) -> Result, String> { + ) -> Result, String> { Ok(Arc::new(self::private_tx::AccountSigner { accounts, passwords: passwords.to_vec(), @@ -278,7 +278,7 @@ mod accounts { pub fn accounts_list( account_provider: Arc, - ) -> Arc Vec
+ Send + Sync> { + ) -> Arc Vec
+ Send + Sync> { Arc::new(move || account_provider.accounts().unwrap_or_default()) } diff --git a/parity/db/rocksdb/mod.rs b/parity/db/rocksdb/mod.rs index 05bd1560d..ba346b97e 100644 --- a/parity/db/rocksdb/mod.rs +++ b/parity/db/rocksdb/mod.rs @@ -37,13 +37,13 @@ mod migration; pub use self::migration::migrate; struct AppDB { - key_value: Arc, + key_value: Arc, blooms: blooms_db::Database, trace_blooms: blooms_db::Database, } impl BlockChainDB for AppDB { - fn key_value(&self) -> &Arc { + fn key_value(&self) -> &Arc { &self.key_value } @@ -58,7 +58,7 @@ impl BlockChainDB for AppDB { /// Open a secret store DB using the given secret store data path. The DB path is one level beneath the data path. #[cfg(feature = "secretstore")] -pub fn open_secretstore_db(data_path: &str) -> Result, String> { +pub fn open_secretstore_db(data_path: &str) -> Result, String> { use std::path::PathBuf; let mut db_path = PathBuf::from(data_path); @@ -75,7 +75,7 @@ pub fn open_secretstore_db(data_path: &str) -> Result, String> { pub fn restoration_db_handler( client_path: &Path, client_config: &ClientConfig, -) -> Box { +) -> Box { let client_db_config = helpers::client_db_config(client_path, client_config); struct RestorationDBHandler { @@ -83,7 +83,7 @@ pub fn restoration_db_handler( } impl BlockChainDBHandler for RestorationDBHandler { - fn open(&self, db_path: &Path) -> io::Result> { + fn open(&self, db_path: &Path) -> io::Result> { open_database(&db_path.to_string_lossy(), &self.config) } } @@ -98,7 +98,7 @@ pub fn open_db( client_path: &str, cache_config: &CacheConfig, compaction: &DatabaseCompactionProfile, -) -> io::Result> { +) -> io::Result> { let path = Path::new(client_path); let db_config = DatabaseConfig { @@ -110,7 +110,10 @@ pub fn open_db( open_database(client_path, &db_config) } -pub fn open_database(client_path: &str, config: &DatabaseConfig) -> io::Result> { +pub fn open_database( + client_path: &str, + config: &DatabaseConfig, +) -> io::Result> { let path = Path::new(client_path); let blooms_path = path.join("blooms"); diff --git a/parity/informant.rs b/parity/informant.rs index 7743c9d79..b2870eb6d 100644 --- a/parity/informant.rs +++ b/parity/informant.rs @@ -127,8 +127,8 @@ pub trait InformantData: Send + Sync { /// Informant data for a full node. pub struct FullNodeInformantData { pub client: Arc, - pub sync: Option>, - pub net: Option>, + pub sync: Option>, + pub net: Option>, } impl InformantData for FullNodeInformantData { @@ -191,7 +191,7 @@ impl InformantData for FullNodeInformantData { /// Informant data for a light node -- note that the network is required. pub struct LightNodeInformantData { - pub client: Arc, + pub client: Arc, pub sync: Arc, pub cache: Arc>, } diff --git a/parity/ipfs.rs b/parity/ipfs.rs index c0b17c90f..4b455c6c0 100644 --- a/parity/ipfs.rs +++ b/parity/ipfs.rs @@ -41,7 +41,7 @@ impl Default for Configuration { pub fn start_server( conf: Configuration, - client: Arc, + client: Arc, ) -> Result, ServerError> { if !conf.enabled { return Ok(None); diff --git a/parity/light_helpers/epoch_fetch.rs b/parity/light_helpers/epoch_fetch.rs index f86d2130f..8fb63cc12 100644 --- a/parity/light_helpers/epoch_fetch.rs +++ b/parity/light_helpers/epoch_fetch.rs @@ -35,7 +35,7 @@ use parking_lot::RwLock; const ALL_VALID_BACKREFS: &str = "no back-references, therefore all back-references valid; qed"; -type BoxFuture = Box>; +type BoxFuture = Box>; /// Allows on-demand fetch of data useful for the light client. pub struct EpochFetch { @@ -88,8 +88,8 @@ impl ChainDataFetcher for EpochFetch { fn epoch_transition( &self, hash: H256, - engine: Arc, - checker: Arc>, + engine: Arc, + checker: Arc>, ) -> Self::Transition { self.request(request::Signal { hash: hash, diff --git a/parity/modules.rs b/parity/modules.rs index 31c324a72..2b2b977c8 100644 --- a/parity/modules.rs +++ b/parity/modules.rs @@ -25,22 +25,22 @@ use ethcore_logger::Config as LogConfig; pub use sync::{EthSync, ManageNetwork, PrivateTxHandler, SyncProvider}; pub type SyncModules = ( - Arc, - Arc, - Arc, + Arc, + Arc, + Arc, mpsc::Sender, ); pub fn sync( config: SyncConfig, network_config: NetworkConfiguration, - chain: Arc, - snapshot_service: Arc, - private_tx_handler: Option>, - provider: Arc, + chain: Arc, + snapshot_service: Arc, + private_tx_handler: Option>, + provider: Arc, _log_settings: &LogConfig, attached_protos: Vec, - connection_filter: Option>, + connection_filter: Option>, ) -> Result { let eth_sync = EthSync::new( Params { @@ -56,9 +56,9 @@ pub fn sync( )?; Ok(( - eth_sync.clone() as Arc, - eth_sync.clone() as Arc, - eth_sync.clone() as Arc, + eth_sync.clone() as Arc, + eth_sync.clone() as Arc, + eth_sync.clone() as Arc, eth_sync.priority_tasks(), )) } diff --git a/parity/rpc_apis.rs b/parity/rpc_apis.rs index ff2ba4a69..ad6cefd2c 100644 --- a/parity/rpc_apis.rs +++ b/parity/rpc_apis.rs @@ -235,16 +235,16 @@ pub trait Dependencies { pub struct FullDependencies { pub signer_service: Arc, pub client: Arc, - pub snapshot: Arc, - pub sync: Arc, - pub net: Arc, + pub snapshot: Arc, + pub sync: Arc, + pub net: Arc, pub accounts: Arc, pub private_tx_service: Option>, pub miner: Arc, pub external_miner: Arc, pub logger: Arc, pub settings: Arc, - pub net_service: Arc, + pub net_service: Arc, pub updater: Arc, pub geth_compatibility: bool, pub experimental_rpcs: bool, @@ -502,7 +502,7 @@ pub struct LightDependencies { pub signer_service: Arc, pub client: Arc, pub sync: Arc, - pub net: Arc, + pub net: Arc, pub accounts: Arc, pub logger: Arc, pub settings: Arc, diff --git a/parity/run.rs b/parity/run.rs index 085efcd19..1516b4cf0 100644 --- a/parity/run.rs +++ b/parity/run.rs @@ -691,7 +691,7 @@ where let private_tx_provider = private_tx_service.provider(); let connection_filter = connection_filter_address.map(|a| { Arc::new(NodeFilter::new( - Arc::downgrade(&client) as Weak, + Arc::downgrade(&client) as Weak, a, )) }); @@ -762,8 +762,8 @@ where None }; - let private_tx_sync: Option> = match cmd.private_tx_enabled { - true => Some(private_tx_service.clone() as Arc), + let private_tx_sync: Option> = match cmd.private_tx_enabled { + true => Some(private_tx_service.clone() as Arc), false => None, }; @@ -779,7 +779,7 @@ where attached_protos, connection_filter .clone() - .map(|f| f as Arc<::sync::ConnectionFilter + 'static>), + .map(|f| f as Arc), ) .map_err(|e| format!("Sync error: {}", e))?; @@ -840,7 +840,7 @@ where // the updater service let updater_fetch = fetch.clone(); let updater = Updater::new( - &Arc::downgrade(&(service.client() as Arc)), + &Arc::downgrade(&(service.client() as Arc)), &Arc::downgrade(&sync_provider), update_policy, hash_fetch::Client::with_fetch(contract_client.clone(), updater_fetch, runtime.executor()), @@ -1002,7 +1002,7 @@ enum RunningClientInner { >, informant: Arc>, client: Arc, - keep_alive: Box, + keep_alive: Box, }, Full { rpc: @@ -1010,7 +1010,7 @@ enum RunningClientInner { informant: Arc>, client: Arc, client_service: Arc, - keep_alive: Box, + keep_alive: Box, }, } diff --git a/parity/secretstore.rs b/parity/secretstore.rs index 930430560..c906b303d 100644 --- a/parity/secretstore.rs +++ b/parity/secretstore.rs @@ -88,7 +88,7 @@ pub struct Dependencies<'a> { /// Blockchain client. pub client: Arc, /// Sync provider. - pub sync: Arc, + pub sync: Arc, /// Miner service. pub miner: Arc, /// Account provider. @@ -138,7 +138,7 @@ mod server { /// Key server pub struct KeyServer { - _key_server: Box, + _key_server: Box, } impl KeyServer { @@ -148,57 +148,58 @@ mod server { deps: Dependencies, executor: Executor, ) -> Result { - let self_secret: Arc = match conf.self_secret.take() { - Some(NodeSecretKey::Plain(secret)) => { - Arc::new(ethcore_secretstore::PlainNodeKeyPair::new( - KeyPair::from_secret(secret) - .map_err(|e| format!("invalid secret: {}", e))?, - )) - } - #[cfg(feature = "accounts")] - Some(NodeSecretKey::KeyStore(account)) => { - // Check if account exists - if !deps.account_provider.has_account(account.clone()) { - return Err(format!( - "Account {} passed as secret store node key is not found", - account - )); + let self_secret: Arc = + match conf.self_secret.take() { + Some(NodeSecretKey::Plain(secret)) => { + Arc::new(ethcore_secretstore::PlainNodeKeyPair::new( + KeyPair::from_secret(secret) + .map_err(|e| format!("invalid secret: {}", e))?, + )) } - - // Check if any passwords have been read from the password file(s) - if deps.accounts_passwords.is_empty() { - return Err(format!( - "No password found for the secret store node account {}", - account - )); - } - - // Attempt to sign in the engine signer. - let password = deps - .accounts_passwords - .iter() - .find(|p| { - deps.account_provider - .sign(account.clone(), Some((*p).clone()), Default::default()) - .is_ok() - }) - .ok_or_else(|| { - format!( - "No valid password for the secret store node account {}", + #[cfg(feature = "accounts")] + Some(NodeSecretKey::KeyStore(account)) => { + // Check if account exists + if !deps.account_provider.has_account(account.clone()) { + return Err(format!( + "Account {} passed as secret store node key is not found", account + )); + } + + // Check if any passwords have been read from the password file(s) + if deps.accounts_passwords.is_empty() { + return Err(format!( + "No password found for the secret store node account {}", + account + )); + } + + // Attempt to sign in the engine signer. + let password = deps + .accounts_passwords + .iter() + .find(|p| { + deps.account_provider + .sign(account.clone(), Some((*p).clone()), Default::default()) + .is_ok() + }) + .ok_or_else(|| { + format!( + "No valid password for the secret store node account {}", + account + ) + })?; + Arc::new( + ethcore_secretstore::KeyStoreNodeKeyPair::new( + deps.account_provider, + account, + password.clone(), ) - })?; - Arc::new( - ethcore_secretstore::KeyStoreNodeKeyPair::new( - deps.account_provider, - account, - password.clone(), + .map_err(|e| format!("{}", e))?, ) - .map_err(|e| format!("{}", e))?, - ) - } - None => return Err("self secret is required when using secretstore".into()), - }; + } + None => return Err("self secret is required when using secretstore".into()), + }; info!( "Starting SecretStore node: {}", diff --git a/parity/whisper.rs b/parity/whisper.rs index 1ee685e1d..f9da44d7f 100644 --- a/parity/whisper.rs +++ b/parity/whisper.rs @@ -45,7 +45,7 @@ pub struct NetPoolHandle { /// Pool handle. handle: Arc>>, /// Network manager. - net: Arc, + net: Arc, } impl PoolHandle for NetPoolHandle { @@ -73,7 +73,10 @@ pub struct RpcFactory { } impl RpcFactory { - pub fn make_handler(&self, net: Arc) -> WhisperClient { + pub fn make_handler( + &self, + net: Arc, + ) -> WhisperClient { let handle = NetPoolHandle { handle: self.net.clone(), net: net, diff --git a/rpc/src/v1/helpers/deprecated.rs b/rpc/src/v1/helpers/deprecated.rs index 3e9d25672..8a9b530a8 100644 --- a/rpc/src/v1/helpers/deprecated.rs +++ b/rpc/src/v1/helpers/deprecated.rs @@ -39,7 +39,7 @@ const PRINT_INTERVAL: Duration = Duration::from_secs(60); pub struct DeprecationNotice Instant> { now: T, next_warning_at: RwLock>, - printer: Box) + Send + Sync>, + printer: Box) + Send + Sync>, } impl Default for DeprecationNotice { diff --git a/rpc/src/v1/helpers/dispatch/full.rs b/rpc/src/v1/helpers/dispatch/full.rs index 166ea2a44..575208e85 100644 --- a/rpc/src/v1/helpers/dispatch/full.rs +++ b/rpc/src/v1/helpers/dispatch/full.rs @@ -139,7 +139,7 @@ impl Dispatcher fn sign

( &self, filled: FilledTransactionRequest, - signer: &Arc, + signer: &Arc, password: SignWith, post_sign: P, ) -> BoxFuture diff --git a/rpc/src/v1/helpers/dispatch/light.rs b/rpc/src/v1/helpers/dispatch/light.rs index 17bacfeaa..226a2fed9 100644 --- a/rpc/src/v1/helpers/dispatch/light.rs +++ b/rpc/src/v1/helpers/dispatch/light.rs @@ -52,7 +52,7 @@ where /// Sync service. pub sync: Arc, /// Header chain client. - pub client: Arc, + pub client: Arc, /// On-demand request service. pub on_demand: Arc, /// Data cache. @@ -75,7 +75,7 @@ where /// For correct operation, the OnDemand service is assumed to be registered as a network handler, pub fn new( sync: Arc, - client: Arc, + client: Arc, on_demand: Arc, cache: Arc>, transaction_queue: Arc>, @@ -238,7 +238,7 @@ where fn sign

( &self, filled: FilledTransactionRequest, - signer: &Arc, + signer: &Arc, password: SignWith, post_sign: P, ) -> BoxFuture @@ -274,7 +274,7 @@ where // TODO: this could be `impl Trait`. pub fn fetch_gas_price_corpus( sync: Arc, - client: Arc, + client: Arc, on_demand: Arc, cache: Arc>, ) -> BoxFuture> diff --git a/rpc/src/v1/helpers/dispatch/mod.rs b/rpc/src/v1/helpers/dispatch/mod.rs index cefdef37d..633704122 100644 --- a/rpc/src/v1/helpers/dispatch/mod.rs +++ b/rpc/src/v1/helpers/dispatch/mod.rs @@ -126,7 +126,7 @@ pub trait Dispatcher: Send + Sync + Clone { fn sign

( &self, filled: FilledTransactionRequest, - signer: &Arc, + signer: &Arc, password: SignWith, post_sign: P, ) -> BoxFuture @@ -311,7 +311,7 @@ impl From<(T, Option)> for WithToken { /// Execute a confirmation payload. pub fn execute( dispatcher: D, - signer: &Arc, + signer: &Arc, payload: ConfirmationPayload, pass: SignWith, ) -> BoxFuture> { diff --git a/rpc/src/v1/helpers/dispatch/prospective_signer.rs b/rpc/src/v1/helpers/dispatch/prospective_signer.rs index a32def84a..b3a25a047 100644 --- a/rpc/src/v1/helpers/dispatch/prospective_signer.rs +++ b/rpc/src/v1/helpers/dispatch/prospective_signer.rs @@ -34,7 +34,7 @@ enum ProspectiveSignerState { } pub struct ProspectiveSigner { - signer: Arc, + signer: Arc, filled: FilledTransactionRequest, chain_id: Option, reserved: nonce::Reserved, @@ -48,7 +48,7 @@ pub struct ProspectiveSigner { impl ProspectiveSigner

{ pub fn new( - signer: Arc, + signer: Arc, filled: FilledTransactionRequest, chain_id: Option, reserved: nonce::Reserved, diff --git a/rpc/src/v1/helpers/external_signer/mod.rs b/rpc/src/v1/helpers/external_signer/mod.rs index cacd06e24..ebaab6897 100644 --- a/rpc/src/v1/helpers/external_signer/mod.rs +++ b/rpc/src/v1/helpers/external_signer/mod.rs @@ -31,7 +31,7 @@ pub use self::signing_queue::{ pub struct SignerService { is_enabled: bool, queue: Arc, - generate_new_token: Box Result + Send + Sync + 'static>, + generate_new_token: Box Result + Send + Sync + 'static>, } impl SignerService { diff --git a/rpc/src/v1/helpers/external_signer/signing_queue.rs b/rpc/src/v1/helpers/external_signer/signing_queue.rs index 102477cea..c450ba798 100644 --- a/rpc/src/v1/helpers/external_signer/signing_queue.rs +++ b/rpc/src/v1/helpers/external_signer/signing_queue.rs @@ -108,7 +108,7 @@ pub type ConfirmationReceiver = oneshot::Receiver; pub struct ConfirmationsQueue { id: Mutex, queue: RwLock>, - on_event: RwLock () + Send + Sync>>>, + on_event: RwLock () + Send + Sync>>>, } impl ConfirmationsQueue { diff --git a/rpc/src/v1/helpers/light_fetch.rs b/rpc/src/v1/helpers/light_fetch.rs index 29aeda5cb..3dff3e425 100644 --- a/rpc/src/v1/helpers/light_fetch.rs +++ b/rpc/src/v1/helpers/light_fetch.rs @@ -92,7 +92,7 @@ where OD: OnDemandRequester + 'static, { /// The light client. - pub client: Arc, + pub client: Arc, /// The on-demand request service. pub on_demand: Arc, /// Handle to the network. @@ -705,7 +705,7 @@ where match maybe_future { Some(recv) => recv, None => Box::new(future::err(errors::network_disabled())) - as Box + Send>, + as Box + Send>, } } @@ -877,7 +877,7 @@ where tx: EthTransaction, hdr: encoded::Header, env_info: ::vm::EnvInfo, - engine: Arc<::ethcore::engines::EthEngine>, + engine: Arc, on_demand: Arc, sync: Arc, } @@ -945,7 +945,7 @@ where failed => Ok(future::Loop::Break(failed)), } }) - })) as Box + Send> + })) as Box + Send> } else { trace!(target: "light_fetch", "Placing execution request for {} gas in on_demand", params.tx.gas); @@ -966,9 +966,9 @@ where }); match proved_future { - Some(fut) => Box::new(fut) as Box + Send>, + Some(fut) => Box::new(fut) as Box + Send>, None => Box::new(future::err(errors::network_disabled())) - as Box + Send>, + as Box + Send>, } } } diff --git a/rpc/src/v1/helpers/subscription_manager.rs b/rpc/src/v1/helpers/subscription_manager.rs index 2a960b83a..506ec1492 100644 --- a/rpc/src/v1/helpers/subscription_manager.rs +++ b/rpc/src/v1/helpers/subscription_manager.rs @@ -105,7 +105,7 @@ impl> GenericPollManager { .is_some() } - pub fn tick(&self) -> Box + Send> { + pub fn tick(&self) -> Box + Send> { let mut futures = Vec::new(); // poll all subscriptions for (id, subscription) in self.subscribers.iter() { diff --git a/rpc/src/v1/impls/eth.rs b/rpc/src/v1/impls/eth.rs index 55ec72b01..054def7c9 100644 --- a/rpc/src/v1/impls/eth.rs +++ b/rpc/src/v1/impls/eth.rs @@ -123,7 +123,7 @@ where client: Arc, snapshot: Arc, sync: Arc, - accounts: Arc Vec

+ Send + Sync>, + accounts: Arc Vec
+ Send + Sync>, miner: Arc, external_miner: Arc, seed_compute: Mutex, @@ -211,7 +211,7 @@ where client: &Arc, snapshot: &Arc, sync: &Arc, - accounts: &Arc Vec
+ Send + Sync>, + accounts: &Arc Vec
+ Send + Sync>, miner: &Arc, em: &Arc, options: EthClientOptions, diff --git a/rpc/src/v1/impls/eth_pubsub.rs b/rpc/src/v1/impls/eth_pubsub.rs index 0d712a7fa..e8fa58634 100644 --- a/rpc/src/v1/impls/eth_pubsub.rs +++ b/rpc/src/v1/impls/eth_pubsub.rs @@ -105,7 +105,7 @@ where { /// Creates a new `EthPubSubClient` for `LightClient`. pub fn light( - client: Arc, + client: Arc, on_demand: Arc, sync: Arc, cache: Arc>, diff --git a/rpc/src/v1/impls/light/eth.rs b/rpc/src/v1/impls/light/eth.rs index 24163be38..58ada9a32 100644 --- a/rpc/src/v1/impls/light/eth.rs +++ b/rpc/src/v1/impls/light/eth.rs @@ -71,7 +71,7 @@ pub struct EthClient< client: Arc, on_demand: Arc, transaction_queue: Arc>, - accounts: Arc Vec
+ Send + Sync>, + accounts: Arc Vec
+ Send + Sync>, cache: Arc>, polls: Mutex>, poll_lifetime: u32, @@ -114,7 +114,7 @@ where client: Arc, on_demand: Arc, transaction_queue: Arc>, - accounts: Arc Vec
+ Send + Sync>, + accounts: Arc Vec
+ Send + Sync>, cache: Arc>, gas_price_percentile: usize, poll_lifetime: u32, diff --git a/rpc/src/v1/impls/light/parity_set.rs b/rpc/src/v1/impls/light/parity_set.rs index bdf13ead1..bd49739dd 100644 --- a/rpc/src/v1/impls/light/parity_set.rs +++ b/rpc/src/v1/impls/light/parity_set.rs @@ -34,14 +34,14 @@ use v1::{ /// Parity-specific rpc interface for operations altering the settings. pub struct ParitySetClient { - client: Arc, - net: Arc, + client: Arc, + net: Arc, fetch: F, } impl ParitySetClient { /// Creates new `ParitySetClient` with given `Fetch`. - pub fn new(client: Arc, net: Arc, fetch: F) -> Self { + pub fn new(client: Arc, net: Arc, fetch: F) -> Self { ParitySetClient { client, net, fetch } } } diff --git a/rpc/src/v1/impls/parity.rs b/rpc/src/v1/impls/parity.rs index 48f3c8ad9..b4213bae2 100644 --- a/rpc/src/v1/impls/parity.rs +++ b/rpc/src/v1/impls/parity.rs @@ -57,13 +57,13 @@ pub struct ParityClient { client: Arc, miner: Arc, updater: Arc, - sync: Arc, - net: Arc, + sync: Arc, + net: Arc, logger: Arc, settings: Arc, signer: Option>, ws_address: Option, - snapshot: Option>, + snapshot: Option>, } impl ParityClient @@ -74,14 +74,14 @@ where pub fn new( client: Arc, miner: Arc, - sync: Arc, + sync: Arc, updater: Arc, - net: Arc, + net: Arc, logger: Arc, settings: Arc, signer: Option>, ws_address: Option, - snapshot: Option>, + snapshot: Option>, ) -> Self { ParityClient { client, diff --git a/rpc/src/v1/impls/parity_set.rs b/rpc/src/v1/impls/parity_set.rs index 6a1d4e60c..42578af91 100644 --- a/rpc/src/v1/impls/parity_set.rs +++ b/rpc/src/v1/impls/parity_set.rs @@ -86,7 +86,7 @@ pub struct ParitySetClient { client: Arc, miner: Arc, updater: Arc, - net: Arc, + net: Arc, fetch: F, } @@ -99,7 +99,7 @@ where client: &Arc, miner: &Arc, updater: &Arc, - net: &Arc, + net: &Arc, fetch: F, ) -> Self { ParitySetClient { diff --git a/rpc/src/v1/impls/signer.rs b/rpc/src/v1/impls/signer.rs index 3d14853e2..5df4add5d 100644 --- a/rpc/src/v1/impls/signer.rs +++ b/rpc/src/v1/impls/signer.rs @@ -52,7 +52,7 @@ use v1::{ /// Transactions confirmation (personal) rpc implementation. pub struct SignerClient { signer: Arc, - accounts: Arc, + accounts: Arc, dispatcher: D, subscribers: Arc>>>>, deprecation_notice: DeprecationNotice, @@ -61,7 +61,7 @@ pub struct SignerClient { impl SignerClient { /// Create new instance of signer client. pub fn new( - accounts: Arc, + accounts: Arc, dispatcher: D, signer: &Arc, executor: Executor, @@ -106,7 +106,7 @@ impl SignerClient { f: F, ) -> BoxFuture> where - F: FnOnce(D, &Arc, ConfirmationPayload) -> T, + F: FnOnce(D, &Arc, ConfirmationPayload) -> T, T: IntoFuture, Error = Error>, T::Future: Send + 'static, { diff --git a/rpc/src/v1/impls/signing.rs b/rpc/src/v1/impls/signing.rs index 28457bd0d..8e99e59cd 100644 --- a/rpc/src/v1/impls/signing.rs +++ b/rpc/src/v1/impls/signing.rs @@ -95,7 +95,7 @@ fn schedule( /// Implementation of functions that require signing when no trusted signer is used. pub struct SigningQueueClient { signer: Arc, - accounts: Arc, + accounts: Arc, dispatcher: D, executor: Executor, // None here means that the request hasn't yet been confirmed @@ -109,7 +109,7 @@ impl SigningQueueClient { signer: &Arc, dispatcher: D, executor: Executor, - accounts: &Arc, + accounts: &Arc, ) -> Self { SigningQueueClient { signer: signer.clone(), diff --git a/rpc/src/v1/impls/signing_unsafe.rs b/rpc/src/v1/impls/signing_unsafe.rs index 277fc9564..f2c93474e 100644 --- a/rpc/src/v1/impls/signing_unsafe.rs +++ b/rpc/src/v1/impls/signing_unsafe.rs @@ -40,14 +40,14 @@ use v1::{ /// Implementation of functions that require signing when no trusted signer is used. pub struct SigningUnsafeClient { - accounts: Arc, + accounts: Arc, dispatcher: D, deprecation_notice: DeprecationNotice, } impl SigningUnsafeClient { /// Creates new SigningUnsafeClient. - pub fn new(accounts: &Arc, dispatcher: D) -> Self { + pub fn new(accounts: &Arc, dispatcher: D) -> Self { SigningUnsafeClient { accounts: accounts.clone(), dispatcher, diff --git a/rpc/src/v1/tests/helpers/miner_service.rs b/rpc/src/v1/tests/helpers/miner_service.rs index e5cbf2a5c..9d70c245f 100644 --- a/rpc/src/v1/tests/helpers/miner_service.rs +++ b/rpc/src/v1/tests/helpers/miner_service.rs @@ -63,7 +63,7 @@ pub struct TestMinerService { /// Minimum gas price pub min_gas_price: RwLock>, /// Signer (if any) - pub signer: RwLock>>, + pub signer: RwLock>>, authoring_params: RwLock, } @@ -110,7 +110,7 @@ impl StateClient for TestMinerService { } impl EngineInfo for TestMinerService { - fn engine(&self) -> &EthEngine { + fn engine(&self) -> &dyn EthEngine { unimplemented!() } } diff --git a/rpc/src/v1/tests/mocked/manage_network.rs b/rpc/src/v1/tests/mocked/manage_network.rs index 60e7055cc..3745687b1 100644 --- a/rpc/src/v1/tests/mocked/manage_network.rs +++ b/rpc/src/v1/tests/mocked/manage_network.rs @@ -37,5 +37,5 @@ impl ManageNetwork for TestManageNetwork { fn num_peers_range(&self) -> RangeInclusive { 25..=50 } - fn with_proto_context(&self, _: ProtocolId, _: &mut FnMut(&NetworkContext)) {} + fn with_proto_context(&self, _: ProtocolId, _: &mut dyn FnMut(&dyn NetworkContext)) {} } diff --git a/rpc/src/v1/tests/mocked/parity.rs b/rpc/src/v1/tests/mocked/parity.rs index e51d2a100..88a137bbb 100644 --- a/rpc/src/v1/tests/mocked/parity.rs +++ b/rpc/src/v1/tests/mocked/parity.rs @@ -42,7 +42,7 @@ pub struct Dependencies { pub updater: Arc, pub logger: Arc, pub settings: Arc, - pub network: Arc, + pub network: Arc, pub ws_address: Option, } diff --git a/rpc/src/v1/tests/mocked/parity_set.rs b/rpc/src/v1/tests/mocked/parity_set.rs index d9de12748..974f19ba1 100644 --- a/rpc/src/v1/tests/mocked/parity_set.rs +++ b/rpc/src/v1/tests/mocked/parity_set.rs @@ -59,7 +59,7 @@ fn parity_set_client( client, miner, updater, - &(net.clone() as Arc), + &(net.clone() as Arc), FakeFetch::new(Some(1)), ) } diff --git a/secret-store/src/key_server.rs b/secret-store/src/key_server.rs index a16b2f746..35c996b92 100644 --- a/secret-store/src/key_server.rs +++ b/secret-store/src/key_server.rs @@ -41,17 +41,17 @@ pub struct KeyServerImpl { /// Secret store key server data. pub struct KeyServerCore { - cluster: Arc, + cluster: Arc, } impl KeyServerImpl { /// Create new key server instance pub fn new( config: &ClusterConfiguration, - key_server_set: Arc, - self_key_pair: Arc, - acl_storage: Arc, - key_storage: Arc, + key_server_set: Arc, + self_key_pair: Arc, + acl_storage: Arc, + key_storage: Arc, executor: Executor, ) -> Result { Ok(KeyServerImpl { @@ -67,7 +67,7 @@ impl KeyServerImpl { } /// Get cluster client reference. - pub fn cluster(&self) -> Arc { + pub fn cluster(&self) -> Arc { self.data.lock().cluster.clone() } } @@ -317,10 +317,10 @@ impl MessageSigner for KeyServerImpl { impl KeyServerCore { pub fn new( config: &ClusterConfiguration, - key_server_set: Arc, - self_key_pair: Arc, - acl_storage: Arc, - key_storage: Arc, + key_server_set: Arc, + self_key_pair: Arc, + acl_storage: Arc, + key_storage: Arc, executor: Executor, ) -> Result { let cconfig = NetClusterConfiguration { diff --git a/secret-store/src/key_server_cluster/admin_sessions/key_version_negotiation_session.rs b/secret-store/src/key_server_cluster/admin_sessions/key_version_negotiation_session.rs index d11d6c6bd..8b32ca62c 100644 --- a/secret-store/src/key_server_cluster/admin_sessions/key_version_negotiation_session.rs +++ b/secret-store/src/key_server_cluster/admin_sessions/key_version_negotiation_session.rs @@ -93,7 +93,7 @@ struct SessionCore { /// Key share. pub key_share: Option, /// Session result computer. - pub result_computer: Arc, + pub result_computer: Arc, /// Session transport. pub transport: T, /// Session nonce. @@ -129,7 +129,7 @@ pub struct SessionParams { /// Key share. pub key_share: Option, /// Session result computer. - pub result_computer: Arc, + pub result_computer: Arc, /// Session transport to communicate to other cluster nodes. pub transport: T, /// Session nonce. @@ -150,7 +150,7 @@ enum SessionState { /// Isolated session transport. pub struct IsolatedSessionTransport { /// Cluster. - pub cluster: Arc, + pub cluster: Arc, /// Key id. pub key_id: SessionId, /// Sub session id. diff --git a/secret-store/src/key_server_cluster/admin_sessions/servers_set_change_session.rs b/secret-store/src/key_server_cluster/admin_sessions/servers_set_change_session.rs index 25621d391..1eef28d54 100644 --- a/secret-store/src/key_server_cluster/admin_sessions/servers_set_change_session.rs +++ b/secret-store/src/key_server_cluster/admin_sessions/servers_set_change_session.rs @@ -93,9 +93,9 @@ struct SessionCore { /// Servers set change session meta (id is computed from new_nodes_set). pub meta: ShareChangeSessionMeta, /// Cluster which allows this node to send messages to other nodes in the cluster. - pub cluster: Arc, + pub cluster: Arc, /// Keys storage. - pub key_storage: Arc, + pub key_storage: Arc, /// Session-level nonce. pub nonce: u64, /// All known nodes. @@ -154,9 +154,9 @@ pub struct SessionParams { /// Session meta (artificial). pub meta: ShareChangeSessionMeta, /// Cluster. - pub cluster: Arc, + pub cluster: Arc, /// Keys storage. - pub key_storage: Arc, + pub key_storage: Arc, /// Session nonce. pub nonce: u64, /// All known nodes. @@ -176,7 +176,7 @@ struct ServersSetChangeConsensusTransport { /// Migration id (if part of auto-migration process). migration_id: Option, /// Cluster. - cluster: Arc, + cluster: Arc, } /// Unknown sessions job transport. @@ -186,7 +186,7 @@ struct UnknownSessionsJobTransport { /// Session-level nonce. nonce: u64, /// Cluster. - cluster: Arc, + cluster: Arc, } /// Key version negotiation transport. @@ -196,7 +196,7 @@ struct ServersSetChangeKeyVersionNegotiationTransport { /// Session-level nonce. nonce: u64, /// Cluster. - cluster: Arc, + cluster: Arc, } impl SessionImpl { diff --git a/secret-store/src/key_server_cluster/admin_sessions/sessions_queue.rs b/secret-store/src/key_server_cluster/admin_sessions/sessions_queue.rs index 0cce7d155..38215eb14 100644 --- a/secret-store/src/key_server_cluster/admin_sessions/sessions_queue.rs +++ b/secret-store/src/key_server_cluster/admin_sessions/sessions_queue.rs @@ -30,7 +30,7 @@ pub struct SessionsQueue { impl SessionsQueue { /// Create new sessions queue. - pub fn new(key_storage: &Arc, unknown_sessions: BTreeSet) -> Self { + pub fn new(key_storage: &Arc, unknown_sessions: BTreeSet) -> Self { // TODO [Opt]: // 1) known sessions - change to iter // 2) unknown sesions - request chunk-by-chunk diff --git a/secret-store/src/key_server_cluster/admin_sessions/share_add_session.rs b/secret-store/src/key_server_cluster/admin_sessions/share_add_session.rs index 689627689..1fb915820 100644 --- a/secret-store/src/key_server_cluster/admin_sessions/share_add_session.rs +++ b/secret-store/src/key_server_cluster/admin_sessions/share_add_session.rs @@ -83,7 +83,7 @@ struct SessionCore { /// Session transport to communicate to other cluster nodes. pub transport: T, /// Key storage. - pub key_storage: Arc, + pub key_storage: Arc, /// Administrator public key. pub admin_public: Option, /// SessionImpl completion condvar. @@ -146,7 +146,7 @@ pub struct SessionParams { /// Session transport. pub transport: T, /// Key storage. - pub key_storage: Arc, + pub key_storage: Arc, /// Administrator public key. pub admin_public: Option, /// Session nonce. @@ -169,7 +169,7 @@ pub struct IsolatedSessionTransport { /// Id numbers of all new nodes. id_numbers: Option>>, /// Cluster. - cluster: Arc, + cluster: Arc, } impl SessionImpl @@ -1058,7 +1058,7 @@ impl IsolatedSessionTransport { session_id: SessionId, version: Option, nonce: u64, - cluster: Arc, + cluster: Arc, ) -> Self { IsolatedSessionTransport { session: session_id, diff --git a/secret-store/src/key_server_cluster/admin_sessions/share_change_session.rs b/secret-store/src/key_server_cluster/admin_sessions/share_change_session.rs index f8829156b..8f8a50849 100644 --- a/secret-store/src/key_server_cluster/admin_sessions/share_change_session.rs +++ b/secret-store/src/key_server_cluster/admin_sessions/share_change_session.rs @@ -49,9 +49,9 @@ pub struct ShareChangeSession { /// Share change session meta. meta: ShareChangeSessionMeta, /// Cluster. - cluster: Arc, + cluster: Arc, /// Key storage. - key_storage: Arc, + key_storage: Arc, /// Key version. key_version: H256, /// Nodes that have reported version ownership. @@ -88,9 +88,9 @@ pub struct ShareChangeSessionParams { /// Share change session meta. pub meta: ShareChangeSessionMeta, /// Cluster. - pub cluster: Arc, + pub cluster: Arc, /// Keys storage. - pub key_storage: Arc, + pub key_storage: Arc, /// Session plan. pub plan: ShareChangeSessionPlan, } @@ -103,7 +103,7 @@ pub struct ShareChangeTransport { /// Session nonce. nonce: u64, /// Cluster. - cluster: Arc, + cluster: Arc, } impl ShareChangeSession { @@ -242,7 +242,7 @@ impl ShareChangeSession { } impl ShareChangeTransport { - pub fn new(session_id: SessionId, nonce: u64, cluster: Arc) -> Self { + pub fn new(session_id: SessionId, nonce: u64, cluster: Arc) -> Self { ShareChangeTransport { session_id: session_id, nonce: nonce, diff --git a/secret-store/src/key_server_cluster/client_sessions/decryption_session.rs b/secret-store/src/key_server_cluster/client_sessions/decryption_session.rs index d9f763f17..958dd4662 100644 --- a/secret-store/src/key_server_cluster/client_sessions/decryption_session.rs +++ b/secret-store/src/key_server_cluster/client_sessions/decryption_session.rs @@ -65,7 +65,7 @@ struct SessionCore { /// Key share. pub key_share: Option, /// Cluster which allows this node to send messages to other nodes in the cluster. - pub cluster: Arc, + pub cluster: Arc, /// Session-level nonce. pub nonce: u64, /// SessionImpl completion condvar. @@ -112,9 +112,9 @@ pub struct SessionParams { /// Key share. pub key_share: Option, /// ACL storage. - pub acl_storage: Arc, + pub acl_storage: Arc, /// Cluster. - pub cluster: Arc, + pub cluster: Arc, /// Session nonce. pub nonce: u64, } @@ -132,7 +132,7 @@ struct DecryptionConsensusTransport { /// Selected key version (on master node). version: Option, /// Cluster. - cluster: Arc, + cluster: Arc, } /// Decryption job transport @@ -148,7 +148,7 @@ struct DecryptionJobTransport { /// Master node id. master_node_id: NodeId, /// Cluster. - cluster: Arc, + cluster: Arc, } /// Session delegation status. diff --git a/secret-store/src/key_server_cluster/client_sessions/encryption_session.rs b/secret-store/src/key_server_cluster/client_sessions/encryption_session.rs index 54977b7d3..e7c845c94 100644 --- a/secret-store/src/key_server_cluster/client_sessions/encryption_session.rs +++ b/secret-store/src/key_server_cluster/client_sessions/encryption_session.rs @@ -49,9 +49,9 @@ pub struct SessionImpl { /// Encrypted data. encrypted_data: Option, /// Key storage. - key_storage: Arc, + key_storage: Arc, /// Cluster which allows this node to send messages to other nodes in the cluster. - cluster: Arc, + cluster: Arc, /// Session nonce. nonce: u64, /// SessionImpl completion condvar. @@ -69,9 +69,9 @@ pub struct SessionParams { /// Encrypted data (result of running generation_session::SessionImpl). pub encrypted_data: Option, /// Key storage. - pub key_storage: Arc, + pub key_storage: Arc, /// Cluster - pub cluster: Arc, + pub cluster: Arc, /// Session nonce. pub nonce: u64, } @@ -396,7 +396,7 @@ pub fn check_encrypted_data(key_share: Option<&DocumentKeyShare>) -> Result<(), /// Update key share with encrypted document key. pub fn update_encrypted_data( - key_storage: &Arc, + key_storage: &Arc, key_id: ServerKeyId, mut key_share: DocumentKeyShare, author: Address, diff --git a/secret-store/src/key_server_cluster/client_sessions/generation_session.rs b/secret-store/src/key_server_cluster/client_sessions/generation_session.rs index 04ce452d2..3b28b99fe 100644 --- a/secret-store/src/key_server_cluster/client_sessions/generation_session.rs +++ b/secret-store/src/key_server_cluster/client_sessions/generation_session.rs @@ -48,9 +48,9 @@ pub struct SessionImpl { /// Public identifier of this node. self_node_id: NodeId, /// Key storage. - key_storage: Option>, + key_storage: Option>, /// Cluster which allows this node to send messages to other nodes in the cluster. - cluster: Arc, + cluster: Arc, /// Session-level nonce. nonce: u64, /// SessionImpl completion condvar. @@ -66,9 +66,9 @@ pub struct SessionParams { /// Id of node, on which this session is running. pub self_node_id: Public, /// Key storage. - pub key_storage: Option>, + pub key_storage: Option>, /// Cluster - pub cluster: Arc, + pub cluster: Arc, /// Session nonce. pub nonce: Option, } diff --git a/secret-store/src/key_server_cluster/client_sessions/signing_session_ecdsa.rs b/secret-store/src/key_server_cluster/client_sessions/signing_session_ecdsa.rs index 74d97cb74..dc46328f9 100644 --- a/secret-store/src/key_server_cluster/client_sessions/signing_session_ecdsa.rs +++ b/secret-store/src/key_server_cluster/client_sessions/signing_session_ecdsa.rs @@ -67,7 +67,7 @@ struct SessionCore { /// Key share. pub key_share: Option, /// Cluster which allows this node to send messages to other nodes in the cluster. - pub cluster: Arc, + pub cluster: Arc, /// Session-level nonce. pub nonce: u64, /// SessionImpl completion condvar. @@ -124,9 +124,9 @@ pub struct SessionParams { /// Key share. pub key_share: Option, /// ACL storage. - pub acl_storage: Arc, + pub acl_storage: Arc, /// Cluster - pub cluster: Arc, + pub cluster: Arc, /// Session nonce. pub nonce: u64, } @@ -142,7 +142,7 @@ struct SigningConsensusTransport { /// Selected key version (on master node). version: Option, /// Cluster. - cluster: Arc, + cluster: Arc, } /// Signing key generation transport. @@ -156,7 +156,7 @@ struct NonceGenerationTransport< /// Session-level nonce. nonce: u64, /// Cluster. - cluster: Arc, + cluster: Arc, /// Other nodes ids. other_nodes_ids: BTreeSet, /// Message mapping function. @@ -172,7 +172,7 @@ struct SigningJobTransport { /// Session-level nonce. nonce: u64, /// Cluster. - cluster: Arc, + cluster: Arc, } /// Session delegation status. diff --git a/secret-store/src/key_server_cluster/client_sessions/signing_session_schnorr.rs b/secret-store/src/key_server_cluster/client_sessions/signing_session_schnorr.rs index b958fa065..4c81f54e2 100644 --- a/secret-store/src/key_server_cluster/client_sessions/signing_session_schnorr.rs +++ b/secret-store/src/key_server_cluster/client_sessions/signing_session_schnorr.rs @@ -67,7 +67,7 @@ struct SessionCore { /// Key share. pub key_share: Option, /// Cluster which allows this node to send messages to other nodes in the cluster. - pub cluster: Arc, + pub cluster: Arc, /// Session-level nonce. pub nonce: u64, /// SessionImpl completion condvar. @@ -121,9 +121,9 @@ pub struct SessionParams { /// Key share. pub key_share: Option, /// ACL storage. - pub acl_storage: Arc, + pub acl_storage: Arc, /// Cluster - pub cluster: Arc, + pub cluster: Arc, /// Session nonce. pub nonce: u64, } @@ -139,7 +139,7 @@ struct SigningConsensusTransport { /// Selected key version (on master node). version: Option, /// Cluster. - cluster: Arc, + cluster: Arc, } /// Signing key generation transport. @@ -147,7 +147,7 @@ struct SessionKeyGenerationTransport { /// Session access key. access_key: Secret, /// Cluster. - cluster: Arc, + cluster: Arc, /// Session-level nonce. nonce: u64, /// Other nodes ids. @@ -163,7 +163,7 @@ struct SigningJobTransport { /// Session-level nonce. nonce: u64, /// Cluster. - cluster: Arc, + cluster: Arc, } /// Session delegation status. diff --git a/secret-store/src/key_server_cluster/cluster.rs b/secret-store/src/key_server_cluster/cluster.rs index 124a215ae..e99b3e3c3 100644 --- a/secret-store/src/key_server_cluster/cluster.rs +++ b/secret-store/src/key_server_cluster/cluster.rs @@ -116,14 +116,20 @@ pub trait ClusterClient: Send + Sync { ) -> Result, Error>; /// Listen for new generation sessions. - fn add_generation_listener(&self, listener: Arc>); + fn add_generation_listener( + &self, + listener: Arc>, + ); /// Listen for new decryption sessions. - fn add_decryption_listener(&self, listener: Arc>); + fn add_decryption_listener( + &self, + listener: Arc>, + ); /// Listen for new key version negotiation sessions. fn add_key_version_negotiation_listener( &self, listener: Arc< - ClusterSessionsListener< + dyn ClusterSessionsListener< KeyVersionNegotiationSession, >, >, @@ -162,13 +168,13 @@ pub trait Cluster: Send + Sync { #[derive(Clone)] pub struct ClusterConfiguration { /// KeyPair this node holds. - pub self_key_pair: Arc, + pub self_key_pair: Arc, /// Cluster nodes set. - pub key_server_set: Arc, + pub key_server_set: Arc, /// Reference to key storage - pub key_storage: Arc, + pub key_storage: Arc, /// Reference to ACL storage - pub acl_storage: Arc, + pub acl_storage: Arc, /// Administrator public key. pub admin_public: Option, /// Do not remove sessions from container. @@ -191,8 +197,8 @@ pub struct ClusterClientImpl { pub struct ClusterView { configured_nodes_count: usize, connected_nodes: BTreeSet, - connections: Arc, - self_key_pair: Arc, + connections: Arc, + self_key_pair: Arc, } /// Cross-thread shareable cluster data. @@ -200,15 +206,15 @@ pub struct ClusterData { /// Cluster configuration. pub config: ClusterConfiguration, /// KeyPair this node holds. - pub self_key_pair: Arc, + pub self_key_pair: Arc, /// Connections data. pub connections: C, /// Active sessions data. pub sessions: Arc, // Messages processor. - pub message_processor: Arc, + pub message_processor: Arc, /// Link between servers set chnage session and the connections manager. - pub servers_set_change_creator_connector: Arc, + pub servers_set_change_creator_connector: Arc, } /// Create new network-backed cluster. @@ -225,7 +231,7 @@ pub fn new_network_cluster( connections: BTreeMap::new(), })); - let connection_trigger: Box = + let connection_trigger: Box = match net_config.auto_migrate_enabled { false => Box::new(SimpleConnectionTrigger::with_config(&config)), true if config.admin_public.is_none() => { @@ -310,9 +316,9 @@ pub fn new_test_cluster( impl ClusterCore { pub fn new( sessions: Arc, - message_processor: Arc, + message_processor: Arc, connections: C, - servers_set_change_creator_connector: Arc, + servers_set_change_creator_connector: Arc, config: ClusterConfiguration, ) -> Result, Error> { Ok(Arc::new(ClusterCore { @@ -328,7 +334,7 @@ impl ClusterCore { } /// Create new client interface. - pub fn client(&self) -> Arc { + pub fn client(&self) -> Arc { Arc::new(ClusterClientImpl::new(self.data.clone())) } @@ -339,7 +345,7 @@ impl ClusterCore { } #[cfg(test)] - pub fn view(&self) -> Result, Error> { + pub fn view(&self) -> Result, Error> { let connections = self.data.connections.provider(); let mut connected_nodes = connections.connected_nodes()?; let disconnected_nodes = connections.disconnected_nodes(); @@ -358,8 +364,8 @@ impl ClusterCore { impl ClusterView { pub fn new( - self_key_pair: Arc, - connections: Arc, + self_key_pair: Arc, + connections: Arc, nodes: BTreeSet, configured_nodes_count: usize, ) -> Self { @@ -703,14 +709,20 @@ impl ClusterClient for ClusterClientImpl { ) } - fn add_generation_listener(&self, listener: Arc>) { + fn add_generation_listener( + &self, + listener: Arc>, + ) { self.data .sessions .generation_sessions .add_listener(listener); } - fn add_decryption_listener(&self, listener: Arc>) { + fn add_decryption_listener( + &self, + listener: Arc>, + ) { self.data .sessions .decryption_sessions @@ -720,7 +732,7 @@ impl ClusterClient for ClusterClientImpl { fn add_key_version_negotiation_listener( &self, listener: Arc< - ClusterSessionsListener< + dyn ClusterSessionsListener< KeyVersionNegotiationSession, >, >, @@ -768,10 +780,10 @@ pub struct ServersSetChangeParams { } pub fn new_servers_set_change_session( - self_key_pair: Arc, + self_key_pair: Arc, sessions: &ClusterSessions, - connections: Arc, - servers_set_change_creator_connector: Arc, + connections: Arc, + servers_set_change_creator_connector: Arc, params: ServersSetChangeParams, ) -> Result, Error> { let session_id = match params.session_id { @@ -956,18 +968,18 @@ pub mod tests { fn add_generation_listener( &self, - _listener: Arc>, + _listener: Arc>, ) { } fn add_decryption_listener( &self, - _listener: Arc>, + _listener: Arc>, ) { } fn add_key_version_negotiation_listener( &self, _listener: Arc< - ClusterSessionsListener< + dyn ClusterSessionsListener< KeyVersionNegotiationSession, >, >, diff --git a/secret-store/src/key_server_cluster/cluster_connections.rs b/secret-store/src/key_server_cluster/cluster_connections.rs index 92ff86dbf..d9f4202a6 100644 --- a/secret-store/src/key_server_cluster/cluster_connections.rs +++ b/secret-store/src/key_server_cluster/cluster_connections.rs @@ -35,7 +35,7 @@ pub trait Connection: Send + Sync { /// Connections manager. Responsible for keeping us connected to all required nodes. pub trait ConnectionManager: 'static + Send + Sync { /// Returns shared reference to connections provider. - fn provider(&self) -> Arc; + fn provider(&self) -> Arc; /// Try to reach all disconnected nodes immediately. This method is exposed mostly for /// tests, where all 'nodes' are starting listening for incoming connections first and /// only after this, they're actually start connecting to each other. @@ -53,7 +53,7 @@ pub trait ConnectionProvider: Send + Sync { /// Returns the set of currently disconnected nodes. fn disconnected_nodes(&self) -> BTreeSet; /// Returns the reference to the active node connection or None if the node is not connected. - fn connection(&self, node: &NodeId) -> Option>; + fn connection(&self, node: &NodeId) -> Option>; } #[cfg(test)] @@ -112,7 +112,7 @@ pub mod tests { } impl ConnectionManager for Arc { - fn provider(&self) -> Arc { + fn provider(&self) -> Arc { self.clone() } @@ -131,7 +131,7 @@ pub mod tests { self.disconnected_nodes.lock().clone() } - fn connection(&self, node: &NodeId) -> Option> { + fn connection(&self, node: &NodeId) -> Option> { match self.connected_nodes.lock().contains(node) { true => Some(Arc::new(TestConnection { from: self.node, diff --git a/secret-store/src/key_server_cluster/cluster_connections_net.rs b/secret-store/src/key_server_cluster/cluster_connections_net.rs index 6d3f9a6b1..88ad3ed06 100644 --- a/secret-store/src/key_server_cluster/cluster_connections_net.rs +++ b/secret-store/src/key_server_cluster/cluster_connections_net.rs @@ -47,7 +47,7 @@ use tokio::{ use tokio_io::IoFuture; /// Empty future. -pub type BoxedEmptyFuture = Box + Send>; +pub type BoxedEmptyFuture = Box + Send>; /// Maintain interval (seconds). Every MAINTAIN_INTERVAL seconds node: /// 1) checks if connected nodes are responding to KeepAlive messages @@ -88,11 +88,11 @@ struct NetConnectionsData { /// Reference to tokio task executor. executor: Executor, /// Key pair of this node. - self_key_pair: Arc, + self_key_pair: Arc, /// Network messages processor. - message_processor: Arc, + message_processor: Arc, /// Connections trigger. - trigger: Mutex>, + trigger: Mutex>, /// Mutable connection data. container: Arc>, } @@ -130,8 +130,8 @@ impl NetConnectionsManager { /// Create new network connections manager. pub fn new( executor: Executor, - message_processor: Arc, - trigger: Box, + message_processor: Arc, + trigger: Box, container: Arc>, config: &ClusterConfiguration, net_config: NetConnectionsManagerConfig, @@ -161,7 +161,7 @@ impl NetConnectionsManager { } impl ConnectionManager for NetConnectionsManager { - fn provider(&self) -> Arc { + fn provider(&self) -> Arc { self.data.container.clone() } @@ -190,7 +190,7 @@ impl ConnectionProvider for RwLock { .collect() } - fn connection(&self, node: &NodeId) -> Option> { + fn connection(&self, node: &NodeId) -> Option> { match self.read().connections.get(node).cloned() { Some(connection) => Some(connection), None => None, diff --git a/secret-store/src/key_server_cluster/cluster_message_processor.rs b/secret-store/src/key_server_cluster/cluster_message_processor.rs index eefadbde6..d142349c0 100644 --- a/secret-store/src/key_server_cluster/cluster_message_processor.rs +++ b/secret-store/src/key_server_cluster/cluster_message_processor.rs @@ -37,7 +37,7 @@ pub trait MessageProcessor: Send + Sync { /// Process disconnect from the remote node. fn process_disconnect(&self, node: &NodeId); /// Process single message from the connection. - fn process_connection_message(&self, connection: Arc, message: Message); + fn process_connection_message(&self, connection: Arc, message: Message); /// Start servers set change session. This is typically used by ConnectionManager when /// it detects that auto-migration session needs to be started. @@ -57,19 +57,19 @@ pub trait MessageProcessor: Send + Sync { /// Bridge between ConnectionManager and ClusterSessions. pub struct SessionsMessageProcessor { - self_key_pair: Arc, - servers_set_change_creator_connector: Arc, + self_key_pair: Arc, + servers_set_change_creator_connector: Arc, sessions: Arc, - connections: Arc, + connections: Arc, } impl SessionsMessageProcessor { /// Create new instance of SessionsMessageProcessor. pub fn new( - self_key_pair: Arc, - servers_set_change_creator_connector: Arc, + self_key_pair: Arc, + servers_set_change_creator_connector: Arc, sessions: Arc, - connections: Arc, + connections: Arc, ) -> Self { SessionsMessageProcessor { self_key_pair, @@ -83,7 +83,7 @@ impl SessionsMessageProcessor { fn process_message, D>( &self, sessions: &ClusterSessionsContainer, - connection: Arc, + connection: Arc, mut message: Message, ) -> Option> where @@ -214,7 +214,7 @@ impl SessionsMessageProcessor { } /// Process single cluster message from the connection. - fn process_cluster_message(&self, connection: Arc, message: ClusterMessage) { + fn process_cluster_message(&self, connection: Arc, message: ClusterMessage) { match message { ClusterMessage::KeepAlive(_) => { let msg = Message::Cluster(ClusterMessage::KeepAliveResponse( @@ -241,7 +241,7 @@ impl MessageProcessor for SessionsMessageProcessor { self.sessions.on_connection_timeout(node); } - fn process_connection_message(&self, connection: Arc, message: Message) { + fn process_connection_message(&self, connection: Arc, message: Message) { trace!(target: "secretstore_net", "{}: received message {} from {}", self.self_key_pair.public(), message, connection.node_id()); diff --git a/secret-store/src/key_server_cluster/cluster_sessions.rs b/secret-store/src/key_server_cluster/cluster_sessions.rs index 19979cdb2..d88ffb8ce 100644 --- a/secret-store/src/key_server_cluster/cluster_sessions.rs +++ b/secret-store/src/key_server_cluster/cluster_sessions.rs @@ -183,7 +183,7 @@ pub struct ClusterSessionsContainer>>, /// Listeners. Lock order: sessions -> listeners. - listeners: Mutex>>>, + listeners: Mutex>>>, /// Sessions container state. container_state: Arc>, /// Do not actually remove sessions. @@ -197,7 +197,7 @@ pub struct QueuedSession { /// Session master. pub master: NodeId, /// Cluster view. - pub cluster_view: Arc, + pub cluster_view: Arc, /// Last keep alive time. pub last_keep_alive_time: Instant, /// Last received message time. @@ -223,7 +223,9 @@ impl ClusterSessions { /// Create new cluster sessions container. pub fn new( config: &ClusterConfiguration, - servers_set_change_session_creator_connector: Arc, + servers_set_change_session_creator_connector: Arc< + dyn ServersSetChangeSessionCreatorConnector, + >, ) -> Self { let container_state = Arc::new(Mutex::new(ClusterSessionsContainerState::Idle)); let creator_core = Arc::new(SessionCreatorCore::new(config)); @@ -350,7 +352,7 @@ where } } - pub fn add_listener(&self, listener: Arc>) { + pub fn add_listener(&self, listener: Arc>) { self.listeners.lock().push(Arc::downgrade(&listener)); } @@ -380,7 +382,7 @@ where pub fn insert( &self, - cluster: Arc, + cluster: Arc, master: NodeId, session_id: S::Id, session_nonce: Option, @@ -496,7 +498,7 @@ where } } - fn notify_listeners) -> ()>(&self, callback: F) { + fn notify_listeners) -> ()>(&self, callback: F) { let mut listeners = self.listeners.lock(); let mut listener_index = 0; while listener_index < listeners.len() { @@ -676,10 +678,10 @@ impl ClusterSession for AdminSession { } pub fn create_cluster_view( - self_key_pair: Arc, - connections: Arc, + self_key_pair: Arc, + connections: Arc, requires_all_connections: bool, -) -> Result, Error> { +) -> Result, Error> { let mut connected_nodes = connections.connected_nodes()?; let disconnected_nodes = connections.disconnected_nodes(); diff --git a/secret-store/src/key_server_cluster/cluster_sessions_creator.rs b/secret-store/src/key_server_cluster/cluster_sessions_creator.rs index 98aad7fcc..4f1427f7d 100644 --- a/secret-store/src/key_server_cluster/cluster_sessions_creator.rs +++ b/secret-store/src/key_server_cluster/cluster_sessions_creator.rs @@ -79,7 +79,7 @@ pub trait ClusterSessionCreator { /// Create cluster session. fn create( &self, - cluster: Arc, + cluster: Arc, master: NodeId, nonce: Option, id: S::Id, @@ -97,9 +97,9 @@ pub struct SessionCreatorCore { /// Self node id. self_node_id: NodeId, /// Reference to key storage - key_storage: Arc, + key_storage: Arc, /// Reference to ACL storage - acl_storage: Arc, + acl_storage: Arc, /// Always-increasing sessions counter. Is used as session nonce to prevent replay attacks: /// 1) during handshake, KeyServers generate new random key to encrypt messages /// => there's no way to use messages from previous connections for replay attacks @@ -180,7 +180,7 @@ impl ClusterSessionCreator for GenerationSessionCreat fn create( &self, - cluster: Arc, + cluster: Arc, master: NodeId, nonce: Option, id: SessionId, @@ -228,7 +228,7 @@ impl ClusterSessionCreator for EncryptionSessionCreat fn create( &self, - cluster: Arc, + cluster: Arc, master: NodeId, nonce: Option, id: SessionId, @@ -286,7 +286,7 @@ impl ClusterSessionCreator for DecryptionSessi fn create( &self, - cluster: Arc, + cluster: Arc, master: NodeId, nonce: Option, id: SessionIdWithSubSession, @@ -357,7 +357,7 @@ impl ClusterSessionCreator for SchnorrSign fn create( &self, - cluster: Arc, + cluster: Arc, master: NodeId, nonce: Option, id: SessionIdWithSubSession, @@ -426,7 +426,7 @@ impl ClusterSessionCreator for EcdsaSigningS fn create( &self, - cluster: Arc, + cluster: Arc, master: NodeId, nonce: Option, id: SessionIdWithSubSession, @@ -483,7 +483,7 @@ impl ClusterSessionCreator, + cluster: Arc, master: NodeId, nonce: Option, id: SessionIdWithSubSession, @@ -530,7 +530,8 @@ pub struct AdminSessionCreator { /// Administrator public. pub admin_public: Option, /// Servers set change sessions creator connector. - pub servers_set_change_session_creator_connector: Arc, + pub servers_set_change_session_creator_connector: + Arc, } impl ClusterSessionCreator for AdminSessionCreator { @@ -580,7 +581,7 @@ impl ClusterSessionCreator for AdminSess fn create( &self, - cluster: Arc, + cluster: Arc, master: NodeId, nonce: Option, id: SessionId, diff --git a/secret-store/src/key_server_cluster/connection_trigger.rs b/secret-store/src/key_server_cluster/connection_trigger.rs index 52a0ff807..654a38226 100644 --- a/secret-store/src/key_server_cluster/connection_trigger.rs +++ b/secret-store/src/key_server_cluster/connection_trigger.rs @@ -55,7 +55,9 @@ pub trait ConnectionTrigger: Send + Sync { /// Maintain active connections. fn maintain_connections(&mut self, connections: &mut NetConnectionsContainer); /// Return connector for the servers set change session creator. - fn servers_set_change_creator_connector(&self) -> Arc; + fn servers_set_change_creator_connector( + &self, + ) -> Arc; } /// Servers set change session creator connector. @@ -74,11 +76,11 @@ pub trait ServersSetChangeSessionCreatorConnector: Send + Sync { /// Simple connection trigger, which only keeps connections to current_set. pub struct SimpleConnectionTrigger { /// Key server set cluster. - key_server_set: Arc, + key_server_set: Arc, /// Trigger connections. connections: TriggerConnections, /// Servers set change session creator connector. - connector: Arc, + connector: Arc, } /// Simple Servers set change session creator connector, which will just return @@ -100,7 +102,7 @@ pub enum ConnectionsAction { /// Trigger connections. pub struct TriggerConnections { /// This node key pair. - pub self_key_pair: Arc, + pub self_key_pair: Arc, } impl SimpleConnectionTrigger { @@ -115,8 +117,8 @@ impl SimpleConnectionTrigger { /// Create new simple connection trigger. pub fn new( - key_server_set: Arc, - self_key_pair: Arc, + key_server_set: Arc, + self_key_pair: Arc, admin_public: Option, ) -> Self { SimpleConnectionTrigger { @@ -158,7 +160,9 @@ impl ConnectionTrigger for SimpleConnectionTrigger { ) } - fn servers_set_change_creator_connector(&self) -> Arc { + fn servers_set_change_creator_connector( + &self, + ) -> Arc { self.connector.clone() } } diff --git a/secret-store/src/key_server_cluster/connection_trigger_with_migration.rs b/secret-store/src/key_server_cluster/connection_trigger_with_migration.rs index 7ba03d1dd..ed843ec35 100644 --- a/secret-store/src/key_server_cluster/connection_trigger_with_migration.rs +++ b/secret-store/src/key_server_cluster/connection_trigger_with_migration.rs @@ -40,9 +40,9 @@ use NodeKeyPair; /// Key servers set change trigger with automated migration procedure. pub struct ConnectionTriggerWithMigration { /// This node key pair. - self_key_pair: Arc, + self_key_pair: Arc, /// Key server set. - key_server_set: Arc, + key_server_set: Arc, /// Last server set state. snapshot: KeyServerSetSnapshot, /// Required connections action. @@ -112,9 +112,9 @@ struct TriggerSession { /// Servers set change session creator connector. connector: Arc, /// This node key pair. - self_key_pair: Arc, + self_key_pair: Arc, /// Key server set. - key_server_set: Arc, + key_server_set: Arc, } impl ConnectionTriggerWithMigration { @@ -124,7 +124,7 @@ impl ConnectionTriggerWithMigration { } /// Create new trigge with migration. - pub fn new(key_server_set: Arc, self_key_pair: Arc) -> Self { + pub fn new(key_server_set: Arc, self_key_pair: Arc) -> Self { let snapshot = key_server_set.snapshot(); let migration = snapshot.migration.clone(); @@ -220,7 +220,9 @@ impl ConnectionTrigger for ConnectionTriggerWithMigration { } } - fn servers_set_change_creator_connector(&self) -> Arc { + fn servers_set_change_creator_connector( + &self, + ) -> Arc { self.session.connector.clone() } } diff --git a/secret-store/src/key_server_cluster/io/deadline.rs b/secret-store/src/key_server_cluster/io/deadline.rs index 6efeff163..a8597cb0d 100644 --- a/secret-store/src/key_server_cluster/io/deadline.rs +++ b/secret-store/src/key_server_cluster/io/deadline.rs @@ -19,7 +19,7 @@ use std::{io, time::Duration}; use tokio::timer::timeout::{Error as TimeoutError, Timeout}; type DeadlineBox = Box< - Future< + dyn Future< Item = DeadlineStatus<::Item>, Error = TimeoutError<::Error>, > + Send, diff --git a/secret-store/src/key_server_cluster/io/handshake.rs b/secret-store/src/key_server_cluster/io/handshake.rs index a0ba89bb7..d9e56d7b5 100644 --- a/secret-store/src/key_server_cluster/io/handshake.rs +++ b/secret-store/src/key_server_cluster/io/handshake.rs @@ -52,7 +52,7 @@ use tokio_io::{AsyncRead, AsyncWrite}; /// Start handshake procedure with another node from the cluster. pub fn handshake( a: A, - self_key_pair: Arc, + self_key_pair: Arc, trusted_nodes: BTreeSet, ) -> Handshake where @@ -70,7 +70,7 @@ where pub fn handshake_with_init_data( a: A, init_data: Result<(H256, KeyPair), Error>, - self_key_pair: Arc, + self_key_pair: Arc, trusted_nodes: BTreeSet, ) -> Handshake where @@ -118,7 +118,7 @@ where } /// Wait for handshake procedure to be started by another node from the cluster. -pub fn accept_handshake(a: A, self_key_pair: Arc) -> Handshake +pub fn accept_handshake(a: A, self_key_pair: Arc) -> Handshake where A: AsyncWrite + AsyncRead, { @@ -173,7 +173,7 @@ pub struct Handshake { is_active: bool, error: Option<(A, Result)>, state: HandshakeState, - self_key_pair: Arc, + self_key_pair: Arc, self_session_key_pair: Option, self_confirmation_plain: H256, trusted_nodes: Option>, @@ -221,7 +221,7 @@ where } fn make_private_key_signature_message( - self_key_pair: &NodeKeyPair, + self_key_pair: &dyn NodeKeyPair, confirmation_plain: &H256, ) -> Result { Ok(Message::Cluster(ClusterMessage::NodePrivateKeySignature( diff --git a/secret-store/src/key_server_cluster/jobs/key_access_job.rs b/secret-store/src/key_server_cluster/jobs/key_access_job.rs index 93b9b16d4..59900ece6 100644 --- a/secret-store/src/key_server_cluster/jobs/key_access_job.rs +++ b/secret-store/src/key_server_cluster/jobs/key_access_job.rs @@ -30,13 +30,13 @@ pub struct KeyAccessJob { /// Has key share? has_key_share: bool, /// ACL storage. - acl_storage: Arc, + acl_storage: Arc, /// Requester data. requester: Option, } impl KeyAccessJob { - pub fn new_on_slave(id: SessionId, acl_storage: Arc) -> Self { + pub fn new_on_slave(id: SessionId, acl_storage: Arc) -> Self { KeyAccessJob { id: id, has_key_share: true, @@ -47,7 +47,7 @@ impl KeyAccessJob { pub fn new_on_master( id: SessionId, - acl_storage: Arc, + acl_storage: Arc, requester: Requester, ) -> Self { KeyAccessJob { diff --git a/secret-store/src/key_server_cluster/jobs/unknown_sessions_job.rs b/secret-store/src/key_server_cluster/jobs/unknown_sessions_job.rs index 5803c4d2e..9f20d4a1c 100644 --- a/secret-store/src/key_server_cluster/jobs/unknown_sessions_job.rs +++ b/secret-store/src/key_server_cluster/jobs/unknown_sessions_job.rs @@ -28,18 +28,18 @@ pub struct UnknownSessionsJob { /// Target node id. target_node_id: Option, /// Keys storage. - key_storage: Arc, + key_storage: Arc, } impl UnknownSessionsJob { - pub fn new_on_slave(key_storage: Arc) -> Self { + pub fn new_on_slave(key_storage: Arc) -> Self { UnknownSessionsJob { target_node_id: None, key_storage: key_storage, } } - pub fn new_on_master(key_storage: Arc, self_node_id: NodeId) -> Self { + pub fn new_on_master(key_storage: Arc, self_node_id: NodeId) -> Self { UnknownSessionsJob { target_node_id: Some(self_node_id), key_storage: key_storage, diff --git a/secret-store/src/key_server_cluster/net/accept_connection.rs b/secret-store/src/key_server_cluster/net/accept_connection.rs index 990b5e50a..ceaea48e0 100644 --- a/secret-store/src/key_server_cluster/net/accept_connection.rs +++ b/secret-store/src/key_server_cluster/net/accept_connection.rs @@ -26,7 +26,7 @@ use tokio::net::TcpStream; /// Create future for accepting incoming connection. pub fn accept_connection( stream: TcpStream, - self_key_pair: Arc, + self_key_pair: Arc, ) -> Deadline { // TODO: This could fail so it would be better either to accept the // address as a separate argument or return a result. diff --git a/secret-store/src/key_server_cluster/net/connect.rs b/secret-store/src/key_server_cluster/net/connect.rs index 4f2e6d712..b633a88c2 100644 --- a/secret-store/src/key_server_cluster/net/connect.rs +++ b/secret-store/src/key_server_cluster/net/connect.rs @@ -26,7 +26,7 @@ use tokio::net::{tcp::ConnectFuture, TcpStream}; /// Create future for connecting to other node. pub fn connect( address: &SocketAddr, - self_key_pair: Arc, + self_key_pair: Arc, trusted_nodes: BTreeSet, ) -> Deadline { let connect = Connect { @@ -49,7 +49,7 @@ enum ConnectState { pub struct Connect { state: ConnectState, address: SocketAddr, - self_key_pair: Arc, + self_key_pair: Arc, trusted_nodes: BTreeSet, } diff --git a/secret-store/src/key_server_set.rs b/secret-store/src/key_server_set.rs index ed76293f9..4b803eab9 100644 --- a/secret-store/src/key_server_set.rs +++ b/secret-store/src/key_server_set.rs @@ -119,14 +119,14 @@ struct CachedContract { /// Previous confirm migration transaction. confirm_migration_tx: Option, /// This node key pair. - self_key_pair: Arc, + self_key_pair: Arc, } impl OnChainKeyServerSet { pub fn new( trusted_client: TrustedClient, contract_address_source: Option, - self_key_pair: Arc, + self_key_pair: Arc, auto_migrate_enabled: bool, key_servers: BTreeMap, ) -> Result, Error> { @@ -253,7 +253,7 @@ impl CachedContract { pub fn new( client: TrustedClient, contract_address_source: Option, - self_key_pair: Arc, + self_key_pair: Arc, auto_migrate_enabled: bool, key_servers: BTreeMap, ) -> Result { @@ -556,7 +556,7 @@ impl CachedContract { key_servers } - fn update_number_of_confirmations_if_required(&mut self, client: &BlockChainClient) { + fn update_number_of_confirmations_if_required(&mut self, client: &dyn BlockChainClient) { if !self.auto_migrate_enabled { return; } @@ -682,11 +682,11 @@ fn update_last_transaction_block( true } -fn latest_block_hash(client: &BlockChainClient) -> H256 { +fn latest_block_hash(client: &dyn BlockChainClient) -> H256 { client.block_hash(BlockId::Latest).unwrap_or_default() } -fn block_confirmations(client: &BlockChainClient, block: H256) -> Option { +fn block_confirmations(client: &dyn BlockChainClient, block: H256) -> Option { client .block_number(BlockId::Hash(block)) .and_then(|block| { diff --git a/secret-store/src/key_storage.rs b/secret-store/src/key_storage.rs index e489cece0..77a2e339f 100644 --- a/secret-store/src/key_storage.rs +++ b/secret-store/src/key_storage.rs @@ -77,17 +77,17 @@ pub trait KeyStorage: Send + Sync { /// Check if storage contains document encryption key fn contains(&self, document: &ServerKeyId) -> bool; /// Iterate through storage - fn iter<'a>(&'a self) -> Box + 'a>; + fn iter<'a>(&'a self) -> Box + 'a>; } /// Persistent document encryption keys storage pub struct PersistentKeyStorage { - db: Arc, + db: Arc, } /// Persistent document encryption keys storage iterator pub struct PersistentKeyStorageIterator<'a> { - iter: Box, Box<[u8]>)> + 'a>, + iter: Box, Box<[u8]>)> + 'a>, } /// V0 of encrypted key share, as it is stored by key storage on the single key server. @@ -172,14 +172,14 @@ type SerializableDocumentKeyShareVersionV3 = SerializableDocumentKeyShareVersion impl PersistentKeyStorage { /// Create new persistent document encryption keys storage - pub fn new(db: Arc) -> Result { + pub fn new(db: Arc) -> Result { let db = upgrade_db(db)?; Ok(PersistentKeyStorage { db: db }) } } -fn upgrade_db(db: Arc) -> Result, Error> { +fn upgrade_db(db: Arc) -> Result, Error> { let version = db.get(None, DB_META_KEY_VERSION)?; let version = version.and_then(|v| v.get(0).cloned()).unwrap_or(0); match version { @@ -331,7 +331,7 @@ impl KeyStorage for PersistentKeyStorage { .unwrap_or(false) } - fn iter<'a>(&'a self) -> Box + 'a> { + fn iter<'a>(&'a self) -> Box + 'a> { Box::new(PersistentKeyStorageIterator { iter: self.db.iter(None), }) @@ -506,7 +506,7 @@ pub mod tests { self.keys.read().contains_key(document) } - fn iter<'a>(&'a self) -> Box + 'a> { + fn iter<'a>(&'a self) -> Box + 'a> { Box::new(self.keys.read().clone().into_iter()) } } diff --git a/secret-store/src/lib.rs b/secret-store/src/lib.rs index 915dc8a3e..f0a46c307 100644 --- a/secret-store/src/lib.rs +++ b/secret-store/src/lib.rs @@ -92,21 +92,23 @@ pub use types::{ /// Start new key server instance pub fn start( client: Arc, - sync: Arc, + sync: Arc, miner: Arc, - self_key_pair: Arc, + self_key_pair: Arc, mut config: ServiceConfiguration, - db: Arc, + db: Arc, executor: Executor, -) -> Result, Error> { +) -> Result, Error> { let trusted_client = trusted_client::TrustedClient::new(self_key_pair.clone(), client.clone(), sync, miner); - let acl_storage: Arc = match config.acl_check_contract_address.take() { - Some(acl_check_contract_address) => { - acl_storage::OnChainAclStorage::new(trusted_client.clone(), acl_check_contract_address)? - } - None => Arc::new(acl_storage::DummyAclStorage::default()), - }; + let acl_storage: Arc = + match config.acl_check_contract_address.take() { + Some(acl_check_contract_address) => acl_storage::OnChainAclStorage::new( + trusted_client.clone(), + acl_check_contract_address, + )?, + None => Arc::new(acl_storage::DummyAclStorage::default()), + }; let key_server_set = key_server_set::OnChainKeyServerSet::new( trusted_client.clone(), @@ -125,7 +127,7 @@ pub fn start( executor.clone(), )?); let cluster = key_server.cluster(); - let key_server: Arc = key_server; + let key_server: Arc = key_server; // prepare HTTP listener let http_listener = match config.listener_address { @@ -148,7 +150,7 @@ pub fn start( )) }; - let mut contracts: Vec> = Vec::new(); + let mut contracts: Vec> = Vec::new(); config .service_contract_address .map(|address| { @@ -212,7 +214,9 @@ pub fn start( }) .map(|l| contracts.push(l)); - let contract: Option> = match contracts.len() { + let contract: Option> = match contracts + .len() + { 0 => None, 1 => Some(contracts.pop().expect("contract.len() is 1; qed")), _ => Some(Arc::new( diff --git a/secret-store/src/listener/http_listener.rs b/secret-store/src/listener/http_listener.rs index 8c4e72d53..73d63980e 100644 --- a/secret-store/src/listener/http_listener.rs +++ b/secret-store/src/listener/http_listener.rs @@ -91,14 +91,14 @@ struct KeyServerHttpHandler { /// Shared http handler struct KeyServerSharedHttpHandler { - key_server: Weak, + key_server: Weak, } impl KeyServerHttpListener { /// Start KeyServer http listener pub fn start( listener_address: NodeAddress, - key_server: Weak, + key_server: Weak, executor: Executor, ) -> Result { let shared_handler = Arc::new(KeyServerSharedHttpHandler { @@ -247,7 +247,7 @@ impl Service for KeyServerHttpHandler { type ReqBody = Body; type ResBody = Body; type Error = hyper::Error; - type Future = Box, Error = Self::Error> + Send>; + type Future = Box, Error = Self::Error> + Send>; fn call(&mut self, req: HttpRequest) -> Self::Future { if req.headers().contains_key(header::ORIGIN) { @@ -515,7 +515,7 @@ mod tests { #[test] fn http_listener_successfully_drops() { - let key_server: Arc = Arc::new(DummyKeyServer::default()); + let key_server: Arc = Arc::new(DummyKeyServer::default()); let address = NodeAddress { address: "127.0.0.1".into(), port: 9000, diff --git a/secret-store/src/listener/mod.rs b/secret-store/src/listener/mod.rs index 2223aec91..de36fa62b 100644 --- a/secret-store/src/listener/mod.rs +++ b/secret-store/src/listener/mod.rs @@ -44,7 +44,7 @@ pub struct ApiMask { /// Combined HTTP + service contract listener. pub struct Listener { - key_server: Arc, + key_server: Arc, _http: Option, _contract: Option>, } @@ -64,7 +64,7 @@ impl ApiMask { impl Listener { /// Create new listener. pub fn new( - key_server: Arc, + key_server: Arc, http: Option, contract: Option>, ) -> Self { diff --git a/secret-store/src/listener/service_contract.rs b/secret-store/src/listener/service_contract.rs index bc9fc181d..98360a91c 100644 --- a/secret-store/src/listener/service_contract.rs +++ b/secret-store/src/listener/service_contract.rs @@ -81,9 +81,9 @@ pub trait ServiceContract: Send + Sync { /// Update contract when new blocks are enacted. Returns true if contract is installed && up-to-date (i.e. chain is synced). fn update(&self) -> bool; /// Read recent contract logs. Returns topics of every entry. - fn read_logs(&self) -> Box>; + fn read_logs(&self) -> Box>; /// Publish generated key. - fn read_pending_requests(&self) -> Box>; + fn read_pending_requests(&self) -> Box>; /// Publish generated server key. fn publish_generated_server_key( &self, @@ -158,7 +158,7 @@ pub struct OnChainServiceContract { /// Blockchain client. client: TrustedClient, /// This node key pair. - self_key_pair: Arc, + self_key_pair: Arc, /// Contract registry name (if any). name: String, /// Contract address source. @@ -201,7 +201,7 @@ impl OnChainServiceContract { client: TrustedClient, name: String, address_source: ContractAddress, - self_key_pair: Arc, + self_key_pair: Arc, ) -> Self { let contract = OnChainServiceContract { mask: mask, @@ -265,7 +265,7 @@ impl OnChainServiceContract { C: 'static + Fn(&Client, &Address, &BlockId) -> Result, R: 'static + Fn( - &NodeKeyPair, + &dyn NodeKeyPair, &Client, &Address, &BlockId, @@ -278,7 +278,7 @@ impl OnChainServiceContract { block: &BlockId, get_count: C, read_item: R, - ) -> Box> { + ) -> Box> { get_count(&*client, contract_address, block) .map(|count| { let client = client.clone(); @@ -297,7 +297,7 @@ impl OnChainServiceContract { }, index: 0.into(), length: count, - }) as Box> + }) as Box> }) .map_err(|error| { warn!(target: "secretstore", "{}: creating pending requests iterator failed: {}", @@ -330,7 +330,7 @@ impl ServiceContract for OnChainServiceContract { self.update_contract_address() && self.client.get().is_some() } - fn read_logs(&self) -> Box> { + fn read_logs(&self) -> Box> { let client = match self.client.get() { Some(client) => client, None => { @@ -416,7 +416,7 @@ impl ServiceContract for OnChainServiceContract { ) } - fn read_pending_requests(&self) -> Box> { + fn read_pending_requests(&self) -> Box> { let client = match self.client.get() { Some(client) => client, None => return Box::new(::std::iter::empty()), @@ -439,7 +439,7 @@ impl ServiceContract for OnChainServiceContract { &ServerKeyGenerationService::read_pending_requests_count, &ServerKeyGenerationService::read_pending_request, )) - as Box>, + as Box>, false => Box::new(::std::iter::empty()), }; let iter = match self.mask.server_key_retrieval_requests { @@ -787,7 +787,7 @@ impl ServerKeyGenerationService { /// Read pending request. fn read_pending_request( - self_key_pair: &NodeKeyPair, + self_key_pair: &dyn NodeKeyPair, client: &Client, contract_address: &Address, block: &BlockId, @@ -881,7 +881,7 @@ impl ServerKeyRetrievalService { /// Read pending request. fn read_pending_request( - self_key_pair: &NodeKeyPair, + self_key_pair: &dyn NodeKeyPair, client: &Client, contract_address: &Address, block: &BlockId, @@ -966,7 +966,7 @@ impl DocumentKeyStoreService { /// Read pending request. fn read_pending_request( - self_key_pair: &NodeKeyPair, + self_key_pair: &dyn NodeKeyPair, client: &Client, contract_address: &Address, block: &BlockId, @@ -1118,7 +1118,7 @@ impl DocumentKeyShadowRetrievalService { /// Read pending request. fn read_pending_request( - self_key_pair: &NodeKeyPair, + self_key_pair: &dyn NodeKeyPair, client: &Client, contract_address: &Address, block: &BlockId, @@ -1237,11 +1237,11 @@ pub mod tests { true } - fn read_logs(&self) -> Box> { + fn read_logs(&self) -> Box> { Box::new(self.logs.clone().into_iter()) } - fn read_pending_requests(&self) -> Box> { + fn read_pending_requests(&self) -> Box> { Box::new(self.pending_requests.clone().into_iter()) } diff --git a/secret-store/src/listener/service_contract_aggregate.rs b/secret-store/src/listener/service_contract_aggregate.rs index 1812e1132..c6a06f88a 100644 --- a/secret-store/src/listener/service_contract_aggregate.rs +++ b/secret-store/src/listener/service_contract_aggregate.rs @@ -24,12 +24,12 @@ use ServerKeyId; /// Aggregated on-chain service contract. pub struct OnChainServiceContractAggregate { /// All hosted service contracts. - contracts: Vec>, + contracts: Vec>, } impl OnChainServiceContractAggregate { /// Create new aggregated service contract listener. - pub fn new(contracts: Vec>) -> Self { + pub fn new(contracts: Vec>) -> Self { debug_assert!(contracts.len() > 1); OnChainServiceContractAggregate { contracts: contracts, @@ -46,16 +46,16 @@ impl ServiceContract for OnChainServiceContractAggregate { result } - fn read_logs(&self) -> Box> { + fn read_logs(&self) -> Box> { self.contracts.iter().fold( - Box::new(::std::iter::empty()) as Box>, + Box::new(::std::iter::empty()) as Box>, |i, c| Box::new(i.chain(c.read_logs())), ) } - fn read_pending_requests(&self) -> Box> { + fn read_pending_requests(&self) -> Box> { self.contracts.iter().fold( - Box::new(::std::iter::empty()) as Box>, + Box::new(::std::iter::empty()) as Box>, |i, c| Box::new(i.chain(c.read_pending_requests())), ) } diff --git a/secret-store/src/listener/service_contract_listener.rs b/secret-store/src/listener/service_contract_listener.rs index 9dd647f01..599e183c6 100644 --- a/secret-store/src/listener/service_contract_listener.rs +++ b/secret-store/src/listener/service_contract_listener.rs @@ -69,17 +69,17 @@ pub struct ServiceContractListener { /// Service contract listener parameters. pub struct ServiceContractListenerParams { /// Service contract. - pub contract: Arc, + pub contract: Arc, /// This node key pair. - pub self_key_pair: Arc, + pub self_key_pair: Arc, /// Key servers set. - pub key_server_set: Arc, + pub key_server_set: Arc, /// ACL storage reference. - pub acl_storage: Arc, + pub acl_storage: Arc, /// Cluster reference. - pub cluster: Arc, + pub cluster: Arc, /// Key storage reference. - pub key_storage: Arc, + pub key_storage: Arc, } /// Service contract listener data. @@ -91,17 +91,17 @@ struct ServiceContractListenerData { /// Service tasks queue. pub tasks_queue: Arc>, /// Service contract. - pub contract: Arc, + pub contract: Arc, /// ACL storage reference. - pub acl_storage: Arc, + pub acl_storage: Arc, /// Cluster client reference. - pub cluster: Arc, + pub cluster: Arc, /// This node key pair. - pub self_key_pair: Arc, + pub self_key_pair: Arc, /// Key servers set. - pub key_server_set: Arc, + pub key_server_set: Arc, /// Key storage reference. - pub key_storage: Arc, + pub key_storage: Arc, } /// Retry-related data. @@ -818,7 +818,7 @@ fn log_service_task_result( /// Returns true when session, related to `server_key_id` must be started on `node`. fn is_processed_by_this_key_server( - key_server_set: &KeyServerSet, + key_server_set: &dyn KeyServerSet, node: &NodeId, server_key_id: &H256, ) -> bool { @@ -881,7 +881,7 @@ mod tests { key_storage } - fn make_servers_set(is_isolated: bool) -> Arc { + fn make_servers_set(is_isolated: bool) -> Arc { Arc::new(MapKeyServerSet::new(is_isolated, vec![ ("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8".parse().unwrap(), "127.0.0.1:8080".parse().unwrap()), @@ -893,11 +893,11 @@ mod tests { } fn make_service_contract_listener( - contract: Option>, + contract: Option>, cluster: Option>, - key_storage: Option>, - acl_storage: Option>, - servers_set: Option>, + key_storage: Option>, + acl_storage: Option>, + servers_set: Option>, ) -> Arc { let contract = contract.unwrap_or_else(|| Arc::new(DummyServiceContract::default())); let cluster = cluster.unwrap_or_else(|| Arc::new(DummyClusterClient::default())); diff --git a/secret-store/src/trusted_client.rs b/secret-store/src/trusted_client.rs index 1b8a2427b..1a122330b 100644 --- a/secret-store/src/trusted_client.rs +++ b/secret-store/src/trusted_client.rs @@ -33,11 +33,11 @@ use NodeKeyPair; /// 'Trusted' client weak reference. pub struct TrustedClient { /// This key server node key pair. - self_key_pair: Arc, + self_key_pair: Arc, /// Blockchain client. client: Weak, /// Sync provider. - sync: Weak, + sync: Weak, /// Miner service. miner: Weak, } @@ -45,9 +45,9 @@ pub struct TrustedClient { impl TrustedClient { /// Create new trusted client. pub fn new( - self_key_pair: Arc, + self_key_pair: Arc, client: Arc, - sync: Arc, + sync: Arc, miner: Arc, ) -> Self { TrustedClient { diff --git a/updater/hash-fetch/src/client.rs b/updater/hash-fetch/src/client.rs index 7b288cbb8..87ee75b21 100644 --- a/updater/hash-fetch/src/client.rs +++ b/updater/hash-fetch/src/client.rs @@ -38,7 +38,7 @@ pub trait HashFetch: Send + Sync + 'static { &self, hash: H256, abort: fetch::Abort, - on_done: Box) + Send>, + on_done: Box) + Send>, ); } @@ -120,13 +120,13 @@ pub struct Client { contract: URLHintContract, fetch: F, executor: Executor, - random_path: Arc PathBuf + Sync + Send>, + random_path: Arc PathBuf + Sync + Send>, } impl Client { /// Creates new instance of the `Client` given on-chain contract client, fetch service and task runner. pub fn with_fetch( - contract: Arc>, + contract: Arc>, fetch: F, executor: Executor, ) -> Self { @@ -144,7 +144,7 @@ impl HashFetch for Client { &self, hash: H256, abort: fetch::Abort, - on_done: Box) + Send>, + on_done: Box) + Send>, ) { debug!(target: "fetch", "Fetching: {:?}", hash); diff --git a/updater/hash-fetch/src/urlhint.rs b/updater/hash-fetch/src/urlhint.rs index c03bfc355..0dffda35a 100644 --- a/updater/hash-fetch/src/urlhint.rs +++ b/updater/hash-fetch/src/urlhint.rs @@ -100,19 +100,21 @@ pub enum URLHintResult { /// URLHint Contract interface pub trait URLHint: Send + Sync { /// Resolves given id to registrar entry. - fn resolve(&self, id: H256) - -> Box, Error = String> + Send>; + fn resolve( + &self, + id: H256, + ) -> Box, Error = String> + Send>; } /// `URLHintContract` API pub struct URLHintContract { registrar: Registrar, - client: Arc>, + client: Arc>, } impl URLHintContract { /// Creates new `URLHintContract` - pub fn new(client: Arc>) -> Self { + pub fn new(client: Arc>) -> Self { URLHintContract { registrar: Registrar::new(client.clone()), client: client, @@ -170,7 +172,7 @@ impl URLHint for URLHintContract { fn resolve( &self, id: H256, - ) -> Box, Error = String> + Send> { + ) -> Box, Error = String> + Send> { let client = self.client.clone(); let future = self diff --git a/updater/src/updater.rs b/updater/src/updater.rs index 5c26ae97b..0bd9e8b80 100644 --- a/updater/src/updater.rs +++ b/updater/src/updater.rs @@ -141,11 +141,11 @@ pub struct Updater< // Useful environmental stuff. update_policy: UpdatePolicy, weak_self: Mutex>>, - client: Weak, - sync: Option>, + client: Weak, + sync: Option>, fetcher: F, operations_client: O, - exit_handler: Mutex>>, + exit_handler: Mutex>>, time_provider: T, rng: R, @@ -194,11 +194,11 @@ pub trait OperationsClient: Send + Sync + 'static { /// `OperationsClient` that delegates calls to the operations contract. pub struct OperationsContractClient { - client: Weak, + client: Weak, } impl OperationsContractClient { - fn new(client: Weak) -> Self { + fn new(client: Weak) -> Self { OperationsContractClient { client } } @@ -395,8 +395,8 @@ impl GenRange for ThreadRngGenRange { impl Updater { /// `Updater` constructor pub fn new( - client: &Weak, - sync: &Weak, + client: &Weak, + sync: &Weak, update_policy: UpdatePolicy, fetcher: fetch::Client, ) -> Arc { @@ -880,7 +880,7 @@ pub mod tests { #[derive(Clone)] struct FakeFetch { - on_done: Arc) + Send>>>>, + on_done: Arc) + Send>>>>, } impl FakeFetch { @@ -902,7 +902,7 @@ pub mod tests { &self, _hash: H256, _abort: fetch::Abort, - on_done: Box) + Send>, + on_done: Box) + Send>, ) { *self.on_done.lock() = Some(on_done); } diff --git a/util/fetch/src/client.rs b/util/fetch/src/client.rs index e6617295b..7f277034e 100644 --- a/util/fetch/src/client.rs +++ b/util/fetch/src/client.rs @@ -286,7 +286,7 @@ impl Client { } impl Fetch for Client { - type Result = Box + Send + 'static>; + type Result = Box + Send + 'static>; fn fetch(&self, request: Request, abort: Abort) -> Self::Result { debug!(target: "fetch", "fetching: {:?}", request.url()); @@ -649,7 +649,7 @@ impl ::std::error::Error for Error { fn description(&self) -> &str { "Fetch client error" } - fn cause(&self) -> Option<&::std::error::Error> { + fn cause(&self) -> Option<&dyn std::error::Error> { None } } @@ -938,7 +938,7 @@ mod test { type ResBody = hyper::Body; type Error = Error; type Future = Box< - Future, Error = Self::Error> + Send + 'static, + dyn Future, Error = Self::Error> + Send + 'static, >; fn call(&mut self, req: hyper::Request) -> Self::Future { diff --git a/util/io/src/service_mio.rs b/util/io/src/service_mio.rs index 1351b1c97..c518ff50a 100644 --- a/util/io/src/service_mio.rs +++ b/util/io/src/service_mio.rs @@ -53,7 +53,7 @@ where Shutdown, /// Register a new protocol handler. AddHandler { - handler: Arc + Send>, + handler: Arc + Send>, }, RemoveHandler { handler_id: HandlerId, @@ -198,7 +198,7 @@ where Message: Send + Sync, { timers: Arc>>, - handlers: Arc>>>>, + handlers: Arc>>>>, workers: Vec, worker_channel: deque::Worker>, work_ready: Arc, @@ -211,7 +211,7 @@ where /// Creates a new instance and registers it with the event loop. pub fn start( event_loop: &mut EventLoop>, - handlers: Arc>>>>, + handlers: Arc>>>>, ) -> Result<(), IoError> { let (worker, stealer) = deque::fifo(); let num_workers = 4; @@ -413,8 +413,8 @@ enum Handlers where Message: Send, { - SharedCollection(Weak>>>>), - Single(Weak>), + SharedCollection(Weak>>>>), + Single(Weak>), } impl Clone for Handlers { @@ -501,7 +501,7 @@ where } /// Create a new synchronous channel to a given handler. - pub fn to_handler(handler: Weak>) -> IoChannel { + pub fn to_handler(handler: Weak>) -> IoChannel { IoChannel { channel: None, handlers: Handlers::Single(handler), @@ -509,7 +509,7 @@ where } fn new( channel: Sender>, - handlers: Weak>>>>, + handlers: Weak>>>>, ) -> IoChannel { IoChannel { channel: Some(channel), @@ -526,7 +526,7 @@ where { thread: Option>, host_channel: Mutex>>, - handlers: Arc>>>>, + handlers: Arc>>>>, } impl IoService @@ -569,7 +569,10 @@ where } /// Regiter an IO handler with the event loop. - pub fn register_handler(&self, handler: Arc + Send>) -> Result<(), IoError> { + pub fn register_handler( + &self, + handler: Arc + Send>, + ) -> Result<(), IoError> { self.host_channel .lock() .send(IoMessage::AddHandler { handler: handler })?; diff --git a/util/io/src/service_non_mio.rs b/util/io/src/service_non_mio.rs index d958a5d23..f9a3f17a7 100644 --- a/util/io/src/service_non_mio.rs +++ b/util/io/src/service_non_mio.rs @@ -222,7 +222,7 @@ where Message: Send + Sync + 'static, { // All the I/O handlers that have been registered. - handlers: RwLock>>>, + handlers: RwLock>>>, // All the background threads, so that we can unpark them. threads: RwLock>, // Used to create timeouts. @@ -317,7 +317,10 @@ where } /// Register an IO handler with the event loop. - pub fn register_handler(&self, handler: Arc + Send>) -> Result<(), IoError> { + pub fn register_handler( + &self, + handler: Arc + Send>, + ) -> Result<(), IoError> { let id = self.shared.handlers.write().insert(handler.clone()); assert!(id <= MAX_HANDLERS, "Too many handlers registered"); let ctxt = IoContext { diff --git a/util/io/src/worker.rs b/util/io/src/worker.rs index f2b81b4e1..789cca0ad 100644 --- a/util/io/src/worker.rs +++ b/util/io/src/worker.rs @@ -44,7 +44,7 @@ pub struct Work { pub work_type: WorkType, pub token: usize, pub handler_id: HandlerId, - pub handler: Arc>, + pub handler: Arc>, } /// An IO worker thread diff --git a/util/journaldb/src/archivedb.rs b/util/journaldb/src/archivedb.rs index bcf984c1a..2fd6b0809 100644 --- a/util/journaldb/src/archivedb.rs +++ b/util/journaldb/src/archivedb.rs @@ -43,14 +43,14 @@ use traits::JournalDB; /// that the states of any block the node has ever processed will be accessible. pub struct ArchiveDB { overlay: MemoryDB, - backing: Arc, + backing: Arc, latest_era: Option, column: Option, } impl ArchiveDB { /// Create a new instance from a key-value db. - pub fn new(backing: Arc, column: Option) -> ArchiveDB { + pub fn new(backing: Arc, column: Option) -> ArchiveDB { let latest_era = backing .get(column, &LATEST_ERA_KEY) .expect("Low-level database error.") @@ -120,7 +120,7 @@ impl ::traits::KeyedHashDB for ArchiveDB { } impl JournalDB for ArchiveDB { - fn boxed_clone(&self) -> Box { + fn boxed_clone(&self) -> Box { Box::new(ArchiveDB { overlay: self.overlay.clone(), backing: self.backing.clone(), @@ -215,7 +215,7 @@ impl JournalDB for ArchiveDB { false } - fn backing(&self) -> &Arc { + fn backing(&self) -> &Arc { &self.backing } diff --git a/util/journaldb/src/as_hash_db_impls.rs b/util/journaldb/src/as_hash_db_impls.rs index 69eb674bb..1f9378595 100644 --- a/util/journaldb/src/as_hash_db_impls.rs +++ b/util/journaldb/src/as_hash_db_impls.rs @@ -26,76 +26,76 @@ use overlayrecentdb::OverlayRecentDB; use refcounteddb::RefCountedDB; impl AsHashDB for ArchiveDB { - fn as_hash_db(&self) -> &HashDB { + fn as_hash_db(&self) -> &dyn HashDB { self } - fn as_hash_db_mut(&mut self) -> &mut HashDB { + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self } } impl AsHashDB for EarlyMergeDB { - fn as_hash_db(&self) -> &HashDB { + fn as_hash_db(&self) -> &dyn HashDB { self } - fn as_hash_db_mut(&mut self) -> &mut HashDB { + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self } } impl AsHashDB for OverlayRecentDB { - fn as_hash_db(&self) -> &HashDB { + fn as_hash_db(&self) -> &dyn HashDB { self } - fn as_hash_db_mut(&mut self) -> &mut HashDB { + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self } } impl AsHashDB for RefCountedDB { - fn as_hash_db(&self) -> &HashDB { + fn as_hash_db(&self) -> &dyn HashDB { self } - fn as_hash_db_mut(&mut self) -> &mut HashDB { + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self } } impl AsHashDB for OverlayDB { - fn as_hash_db(&self) -> &HashDB { + fn as_hash_db(&self) -> &dyn HashDB { self } - fn as_hash_db_mut(&mut self) -> &mut HashDB { + fn as_hash_db_mut(&mut self) -> &mut dyn HashDB { self } } impl AsKeyedHashDB for ArchiveDB { - fn as_keyed_hash_db(&self) -> &KeyedHashDB { + fn as_keyed_hash_db(&self) -> &dyn KeyedHashDB { self } } impl AsKeyedHashDB for EarlyMergeDB { - fn as_keyed_hash_db(&self) -> &KeyedHashDB { + fn as_keyed_hash_db(&self) -> &dyn KeyedHashDB { self } } impl AsKeyedHashDB for OverlayRecentDB { - fn as_keyed_hash_db(&self) -> &KeyedHashDB { + fn as_keyed_hash_db(&self) -> &dyn KeyedHashDB { self } } impl AsKeyedHashDB for RefCountedDB { - fn as_keyed_hash_db(&self) -> &KeyedHashDB { + fn as_keyed_hash_db(&self) -> &dyn KeyedHashDB { self } } impl AsKeyedHashDB for OverlayDB { - fn as_keyed_hash_db(&self) -> &KeyedHashDB { + fn as_keyed_hash_db(&self) -> &dyn KeyedHashDB { self } } diff --git a/util/journaldb/src/earlymergedb.rs b/util/journaldb/src/earlymergedb.rs index 37c821d90..1e51bf788 100644 --- a/util/journaldb/src/earlymergedb.rs +++ b/util/journaldb/src/earlymergedb.rs @@ -113,7 +113,7 @@ enum RemoveFrom { /// TODO: `store_reclaim_period` pub struct EarlyMergeDB { overlay: MemoryDB, - backing: Arc, + backing: Arc, refs: Option>>>, latest_era: Option, column: Option, @@ -121,7 +121,7 @@ pub struct EarlyMergeDB { impl EarlyMergeDB { /// Create a new instance from file - pub fn new(backing: Arc, col: Option) -> EarlyMergeDB { + pub fn new(backing: Arc, col: Option) -> EarlyMergeDB { let (latest_era, refs) = EarlyMergeDB::read_refs(&*backing, col); let refs = Some(Arc::new(RwLock::new(refs))); EarlyMergeDB { @@ -146,7 +146,7 @@ impl EarlyMergeDB { fn reset_already_in(batch: &mut DBTransaction, col: Option, key: &H256) { batch.delete(col, &Self::morph_key(key, 0)); } - fn is_already_in(backing: &KeyValueDB, col: Option, key: &H256) -> bool { + fn is_already_in(backing: &dyn KeyValueDB, col: Option, key: &H256) -> bool { backing .get(col, &Self::morph_key(key, 0)) .expect("Low-level database error. Some issue with your hard disk?") @@ -155,7 +155,7 @@ impl EarlyMergeDB { fn insert_keys( inserts: &[(H256, DBValue)], - backing: &KeyValueDB, + backing: &dyn KeyValueDB, col: Option, refs: &mut HashMap, batch: &mut DBTransaction, @@ -196,7 +196,7 @@ impl EarlyMergeDB { fn replay_keys( inserts: &[H256], - backing: &KeyValueDB, + backing: &dyn KeyValueDB, col: Option, refs: &mut HashMap, ) { @@ -313,7 +313,7 @@ impl EarlyMergeDB { .expect("Low-level database error. Some issue with your hard disk?") } - fn read_refs(db: &KeyValueDB, col: Option) -> (Option, HashMap) { + fn read_refs(db: &dyn KeyValueDB, col: Option) -> (Option, HashMap) { let mut refs = HashMap::new(); let mut latest_era = None; if let Some(val) = db @@ -392,7 +392,7 @@ impl ::traits::KeyedHashDB for EarlyMergeDB { } impl JournalDB for EarlyMergeDB { - fn boxed_clone(&self) -> Box { + fn boxed_clone(&self) -> Box { Box::new(EarlyMergeDB { overlay: self.overlay.clone(), backing: self.backing.clone(), @@ -409,7 +409,7 @@ impl JournalDB for EarlyMergeDB { .is_none() } - fn backing(&self) -> &Arc { + fn backing(&self) -> &Arc { &self.backing } diff --git a/util/journaldb/src/lib.rs b/util/journaldb/src/lib.rs index fc8d2b82a..6636884bb 100644 --- a/util/journaldb/src/lib.rs +++ b/util/journaldb/src/lib.rs @@ -147,10 +147,10 @@ impl fmt::Display for Algorithm { /// Create a new `JournalDB` trait object over a generic key-value database. pub fn new( - backing: Arc<::kvdb::KeyValueDB>, + backing: Arc, algorithm: Algorithm, col: Option, -) -> Box { +) -> Box { match algorithm { Algorithm::Archive => Box::new(archivedb::ArchiveDB::new(backing, col)), Algorithm::EarlyMerge => Box::new(earlymergedb::EarlyMergeDB::new(backing, col)), diff --git a/util/journaldb/src/overlaydb.rs b/util/journaldb/src/overlaydb.rs index 00551cb09..b75fd14f8 100644 --- a/util/journaldb/src/overlaydb.rs +++ b/util/journaldb/src/overlaydb.rs @@ -41,7 +41,7 @@ use rlp::{decode, encode, Decodable, DecoderError, Encodable, Rlp, RlpStream}; #[derive(Clone)] pub struct OverlayDB { overlay: MemoryDB, - backing: Arc, + backing: Arc, column: Option, } @@ -77,7 +77,7 @@ impl Decodable for Payload { impl OverlayDB { /// Create a new instance of OverlayDB given a `backing` database. - pub fn new(backing: Arc, col: Option) -> OverlayDB { + pub fn new(backing: Arc, col: Option) -> OverlayDB { OverlayDB { overlay: ::new_memory_db(), backing: backing, diff --git a/util/journaldb/src/overlayrecentdb.rs b/util/journaldb/src/overlayrecentdb.rs index 5dff8b2fd..be2f58ba6 100644 --- a/util/journaldb/src/overlayrecentdb.rs +++ b/util/journaldb/src/overlayrecentdb.rs @@ -68,7 +68,7 @@ use util::DatabaseKey; pub struct OverlayRecentDB { transaction_overlay: MemoryDB, - backing: Arc, + backing: Arc, journal_overlay: Arc>, column: Option, } @@ -159,7 +159,7 @@ impl Clone for OverlayRecentDB { impl OverlayRecentDB { /// Create a new instance. - pub fn new(backing: Arc, col: Option) -> OverlayRecentDB { + pub fn new(backing: Arc, col: Option) -> OverlayRecentDB { let journal_overlay = Arc::new(RwLock::new(OverlayRecentDB::read_overlay(&*backing, col))); OverlayRecentDB { transaction_overlay: ::new_memory_db(), @@ -186,7 +186,7 @@ impl OverlayRecentDB { .expect("Low-level database error. Some issue with your hard disk?") } - fn read_overlay(db: &KeyValueDB, col: Option) -> JournalOverlay { + fn read_overlay(db: &dyn KeyValueDB, col: Option) -> JournalOverlay { let mut journal = HashMap::new(); let mut overlay = ::new_memory_db(); let mut count = 0; @@ -285,7 +285,7 @@ impl ::traits::KeyedHashDB for OverlayRecentDB { } impl JournalDB for OverlayRecentDB { - fn boxed_clone(&self) -> Box { + fn boxed_clone(&self) -> Box { Box::new(self.clone()) } @@ -311,7 +311,7 @@ impl JournalDB for OverlayRecentDB { .is_none() } - fn backing(&self) -> &Arc { + fn backing(&self) -> &Arc { &self.backing } diff --git a/util/journaldb/src/refcounteddb.rs b/util/journaldb/src/refcounteddb.rs index 7e83e396c..864137bb7 100644 --- a/util/journaldb/src/refcounteddb.rs +++ b/util/journaldb/src/refcounteddb.rs @@ -52,7 +52,7 @@ use util::{DatabaseKey, DatabaseValueRef, DatabaseValueView}; // TODO: store last_era, reclaim_period. pub struct RefCountedDB { forward: OverlayDB, - backing: Arc, + backing: Arc, latest_era: Option, inserts: Vec, removes: Vec, @@ -61,7 +61,7 @@ pub struct RefCountedDB { impl RefCountedDB { /// Create a new instance given a `backing` database. - pub fn new(backing: Arc, column: Option) -> RefCountedDB { + pub fn new(backing: Arc, column: Option) -> RefCountedDB { let latest_era = backing .get(column, &LATEST_ERA_KEY) .expect("Low-level database error.") @@ -106,7 +106,7 @@ impl ::traits::KeyedHashDB for RefCountedDB { } impl JournalDB for RefCountedDB { - fn boxed_clone(&self) -> Box { + fn boxed_clone(&self) -> Box { Box::new(RefCountedDB { forward: self.forward.clone(), backing: self.backing.clone(), @@ -125,7 +125,7 @@ impl JournalDB for RefCountedDB { self.latest_era.is_none() } - fn backing(&self) -> &Arc { + fn backing(&self) -> &Arc { &self.backing } diff --git a/util/journaldb/src/traits.rs b/util/journaldb/src/traits.rs index da0b656c4..c70171bf1 100644 --- a/util/journaldb/src/traits.rs +++ b/util/journaldb/src/traits.rs @@ -34,14 +34,14 @@ pub trait KeyedHashDB: HashDB { /// Upcast to `KeyedHashDB` pub trait AsKeyedHashDB: AsHashDB { /// Perform upcast to KeyedHashDB. - fn as_keyed_hash_db(&self) -> &KeyedHashDB; + fn as_keyed_hash_db(&self) -> &dyn KeyedHashDB; } /// A `HashDB` which can manage a short-term journal potentially containing many forks of mutually /// exclusive actions. pub trait JournalDB: KeyedHashDB { /// Return a copy of ourself, in a box. - fn boxed_clone(&self) -> Box; + fn boxed_clone(&self) -> Box; /// Returns heap memory size used fn mem_used(&self) -> usize; @@ -90,7 +90,7 @@ pub trait JournalDB: KeyedHashDB { } /// Get backing database. - fn backing(&self) -> &Arc; + fn backing(&self) -> &Arc; /// Clear internal strucutres. This should called after changes have been written /// to the backing strage diff --git a/util/migration-rocksdb/src/lib.rs b/util/migration-rocksdb/src/lib.rs index 38af27a62..bf4aa592e 100644 --- a/util/migration-rocksdb/src/lib.rs +++ b/util/migration-rocksdb/src/lib.rs @@ -36,7 +36,7 @@ use kvdb_rocksdb::{CompactionProfile, Database, DatabaseConfig}; fn other_io_err(e: E) -> io::Error where - E: Into>, + E: Into>, { io::Error::new(io::ErrorKind::Other, e) } @@ -252,7 +252,7 @@ impl TempIndex { /// Manages database migration. pub struct Manager { config: Config, - migrations: Vec>, + migrations: Vec>, } impl Manager { @@ -367,7 +367,7 @@ impl Manager { } /// Find all needed migrations. - fn migrations_from(&mut self, version: u32) -> Vec<&mut Box> { + fn migrations_from(&mut self, version: u32) -> Vec<&mut Box> { self.migrations .iter_mut() .filter(|m| m.version() > version) diff --git a/util/network-devp2p/src/host.rs b/util/network-devp2p/src/host.rs index 286070676..9b8de8da1 100644 --- a/util/network-devp2p/src/host.rs +++ b/util/network-devp2p/src/host.rs @@ -287,19 +287,19 @@ pub struct Host { sessions: Arc>>, discovery: Mutex>>, nodes: RwLock, - handlers: RwLock>>, + handlers: RwLock>>, timers: RwLock>, timer_counter: RwLock, reserved_nodes: RwLock>, stopping: AtomicBool, - filter: Option>, + filter: Option>, } impl Host { /// Create a new instance pub fn new( mut config: NetworkConfiguration, - filter: Option>, + filter: Option>, ) -> Result { let mut listen_address = match config.listen_address { None => SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), DEFAULT_PORT)), @@ -1130,7 +1130,7 @@ impl Host { pub fn with_context(&self, protocol: ProtocolId, io: &IoContext, action: F) where - F: FnOnce(&NetworkContextTrait), + F: FnOnce(&dyn NetworkContextTrait), { let reserved = { self.reserved_nodes.read() }; @@ -1145,7 +1145,7 @@ impl Host { action: F, ) -> T where - F: FnOnce(&NetworkContextTrait) -> T, + F: FnOnce(&dyn NetworkContextTrait) -> T, { let reserved = { self.reserved_nodes.read() }; diff --git a/util/network-devp2p/src/service.rs b/util/network-devp2p/src/service.rs index 19e128003..d7e873858 100644 --- a/util/network-devp2p/src/service.rs +++ b/util/network-devp2p/src/service.rs @@ -48,14 +48,14 @@ pub struct NetworkService { host: RwLock>>, host_handler: Arc, config: NetworkConfiguration, - filter: Option>, + filter: Option>, } impl NetworkService { /// Starts IO event loop pub fn new( config: NetworkConfiguration, - filter: Option>, + filter: Option>, ) -> Result { let host_handler = Arc::new(HostHandler { public_url: RwLock::new(None), @@ -75,7 +75,7 @@ impl NetworkService { /// Register a new protocol handler with the event loop. pub fn register_protocol( &self, - handler: Arc, + handler: Arc, protocol: ProtocolId, // version id + packet count versions: &[(u8, u8)], @@ -192,7 +192,7 @@ impl NetworkService { /// Executes action in the network context pub fn with_context(&self, protocol: ProtocolId, action: F) where - F: FnOnce(&NetworkContext), + F: FnOnce(&dyn NetworkContext), { let io = IoContext::new(self.io_service.channel(), 0); let host = self.host.read(); @@ -204,7 +204,7 @@ impl NetworkService { /// Evaluates function in the network context pub fn with_context_eval(&self, protocol: ProtocolId, action: F) -> Option where - F: FnOnce(&NetworkContext) -> T, + F: FnOnce(&dyn NetworkContext) -> T, { let io = IoContext::new(self.io_service.channel(), 0); let host = self.host.read(); diff --git a/util/network-devp2p/tests/tests.rs b/util/network-devp2p/tests/tests.rs index 83e5d7a92..0c013885d 100644 --- a/util/network-devp2p/tests/tests.rs +++ b/util/network-devp2p/tests/tests.rs @@ -76,16 +76,16 @@ impl TestProtocol { } impl NetworkProtocolHandler for TestProtocol { - fn initialize(&self, io: &NetworkContext) { + fn initialize(&self, io: &dyn NetworkContext) { io.register_timer(0, Duration::from_millis(10)).unwrap(); } - fn read(&self, _io: &NetworkContext, _peer: &PeerId, packet_id: u8, data: &[u8]) { + fn read(&self, _io: &dyn NetworkContext, _peer: &PeerId, packet_id: u8, data: &[u8]) { assert_eq!(packet_id, 33); self.packet.lock().extend(data); } - fn connected(&self, io: &NetworkContext, peer: &PeerId) { + fn connected(&self, io: &dyn NetworkContext, peer: &PeerId) { assert!(io.peer_client_version(*peer).to_string().contains("Parity")); if self.drop_session { io.disconnect_peer(*peer) @@ -94,12 +94,12 @@ impl NetworkProtocolHandler for TestProtocol { } } - fn disconnected(&self, _io: &NetworkContext, _peer: &PeerId) { + fn disconnected(&self, _io: &dyn NetworkContext, _peer: &PeerId) { self.got_disconnect.store(true, AtomicOrdering::Relaxed); } /// Timer function called after a timeout created with `NetworkContext::timeout`. - fn timeout(&self, _io: &NetworkContext, timer: TimerToken) { + fn timeout(&self, _io: &dyn NetworkContext, timer: TimerToken) { assert_eq!(timer, 0); self.got_timeout.store(true, AtomicOrdering::Relaxed); } diff --git a/util/network/src/lib.rs b/util/network/src/lib.rs index ed5c47d6d..742f85c1b 100644 --- a/util/network/src/lib.rs +++ b/util/network/src/lib.rs @@ -80,7 +80,7 @@ pub enum NetworkIoMessage { /// Register a new protocol handler. AddHandler { /// Handler shared instance. - handler: Arc, + handler: Arc, /// Protocol Id. protocol: ProtocolId, /// Supported protocol versions and number of packet IDs reserved by the protocol (packet count). @@ -393,15 +393,15 @@ where /// `Message` is the type for message data. pub trait NetworkProtocolHandler: Sync + Send { /// Initialize the handler - fn initialize(&self, _io: &NetworkContext) {} + fn initialize(&self, _io: &dyn NetworkContext) {} /// Called when new network packet received. - fn read(&self, io: &NetworkContext, peer: &PeerId, packet_id: u8, data: &[u8]); + fn read(&self, io: &dyn NetworkContext, peer: &PeerId, packet_id: u8, data: &[u8]); /// Called when new peer is connected. Only called when peer supports the same protocol. - fn connected(&self, io: &NetworkContext, peer: &PeerId); + fn connected(&self, io: &dyn NetworkContext, peer: &PeerId); /// Called when a previously connected peer disconnects. - fn disconnected(&self, io: &NetworkContext, peer: &PeerId); + fn disconnected(&self, io: &dyn NetworkContext, peer: &PeerId); /// Timer function called after a timeout created with `NetworkContext::timeout`. - fn timeout(&self, _io: &NetworkContext, _timer: TimerToken) {} + fn timeout(&self, _io: &dyn NetworkContext, _timer: TimerToken) {} } /// Non-reserved peer modes. diff --git a/util/registrar/src/registrar.rs b/util/registrar/src/registrar.rs index 7dc290e13..d548df309 100644 --- a/util/registrar/src/registrar.rs +++ b/util/registrar/src/registrar.rs @@ -24,18 +24,18 @@ use_contract!(registrar, "res/registrar.json"); // Maps a domain name to an Ethereum address const DNS_A_RECORD: &'static str = "A"; -pub type Asynchronous = Box + Send>; +pub type Asynchronous = Box + Send>; pub type Synchronous = Result; /// Registrar is dedicated interface to access the registrar contract /// which in turn generates an address when a client requests one pub struct Registrar { - client: Arc>, + client: Arc>, } impl Registrar { /// Registrar constructor - pub fn new(client: Arc>) -> Self { + pub fn new(client: Arc>) -> Self { Self { client: client } } @@ -43,7 +43,7 @@ impl Registrar { pub fn get_address<'a>( &self, key: &'a str, - ) -> Box + Send> { + ) -> Box + Send> { // Address of the registrar itself let registrar_address = match self.client.registrar_address() { Ok(a) => a, diff --git a/util/rlp-compress/src/lib.rs b/util/rlp-compress/src/lib.rs index 9751373eb..606284a9c 100644 --- a/util/rlp-compress/src/lib.rs +++ b/util/rlp-compress/src/lib.rs @@ -39,7 +39,7 @@ pub trait Decompressor { } /// Call this function to compress rlp. -pub fn compress(c: &[u8], swapper: &Compressor) -> ElasticArray1024 { +pub fn compress(c: &[u8], swapper: &dyn Compressor) -> ElasticArray1024 { let rlp = Rlp::new(c); if rlp.is_data() { ElasticArray1024::from_slice( @@ -53,7 +53,7 @@ pub fn compress(c: &[u8], swapper: &Compressor) -> ElasticArray1024 { } /// Call this function to decompress rlp. -pub fn decompress(c: &[u8], swapper: &Decompressor) -> ElasticArray1024 { +pub fn decompress(c: &[u8], swapper: &dyn Decompressor) -> ElasticArray1024 { let rlp = Rlp::new(c); if rlp.is_data() { ElasticArray1024::from_slice( diff --git a/whisper/cli/src/main.rs b/whisper/cli/src/main.rs index b2b837ddc..fe71e3ef3 100644 --- a/whisper/cli/src/main.rs +++ b/whisper/cli/src/main.rs @@ -123,7 +123,11 @@ impl whisper::rpc::PoolHandle for WhisperPoolHandle { } impl WhisperPoolHandle { - fn with_proto_context(&self, proto: net::ProtocolId, f: &mut FnMut(&net::NetworkContext)) { + fn with_proto_context( + &self, + proto: net::ProtocolId, + f: &mut dyn FnMut(&dyn net::NetworkContext), + ) { self.net.with_context_eval(proto, f); } } diff --git a/whisper/src/net/mod.rs b/whisper/src/net/mod.rs index a48a9f022..90f7ca212 100644 --- a/whisper/src/net/mod.rs +++ b/whisper/src/net/mod.rs @@ -721,26 +721,26 @@ impl Network { } impl ::network::NetworkProtocolHandler for Network { - fn initialize(&self, io: &NetworkContext) { + fn initialize(&self, io: &dyn NetworkContext) { // set up broadcast timer (< 1s) io.register_timer(RALLY_TOKEN, RALLY_TIMEOUT) .expect("Failed to initialize message rally timer"); } - fn read(&self, io: &NetworkContext, peer: &PeerId, packet_id: u8, data: &[u8]) { + fn read(&self, io: &dyn NetworkContext, peer: &PeerId, packet_id: u8, data: &[u8]) { self.on_packet(io, peer, packet_id, data) } - fn connected(&self, io: &NetworkContext, peer: &PeerId) { + fn connected(&self, io: &dyn NetworkContext, peer: &PeerId) { // peer with higher ID should begin rallying. self.on_connect(io, peer) } - fn disconnected(&self, _io: &NetworkContext, peer: &PeerId) { + fn disconnected(&self, _io: &dyn NetworkContext, peer: &PeerId) { self.on_disconnect(peer) } - fn timeout(&self, io: &NetworkContext, timer: TimerToken) { + fn timeout(&self, io: &dyn NetworkContext, timer: TimerToken) { // rally with each peer and handle timeouts. match timer { RALLY_TOKEN => self.rally(io), @@ -754,13 +754,13 @@ impl ::network::NetworkProtocolHandler for Network { pub struct ParityExtensions; impl ::network::NetworkProtocolHandler for ParityExtensions { - fn initialize(&self, _io: &NetworkContext) {} + fn initialize(&self, _io: &dyn NetworkContext) {} - fn read(&self, _io: &NetworkContext, _peer: &PeerId, _id: u8, _msg: &[u8]) {} + fn read(&self, _io: &dyn NetworkContext, _peer: &PeerId, _id: u8, _msg: &[u8]) {} - fn connected(&self, _io: &NetworkContext, _peer: &PeerId) {} + fn connected(&self, _io: &dyn NetworkContext, _peer: &PeerId) {} - fn disconnected(&self, _io: &NetworkContext, _peer: &PeerId) {} + fn disconnected(&self, _io: &dyn NetworkContext, _peer: &PeerId) {} - fn timeout(&self, _io: &NetworkContext, _timer: TimerToken) {} + fn timeout(&self, _io: &dyn NetworkContext, _timer: TimerToken) {} } diff --git a/whisper/src/rpc/filter.rs b/whisper/src/rpc/filter.rs index 05282782c..599d9069d 100644 --- a/whisper/src/rpc/filter.rs +++ b/whisper/src/rpc/filter.rs @@ -55,7 +55,7 @@ enum FilterEntry { pub struct Manager { key_store: Arc>, filters: RwLock>, - tx: Mutex>>, + tx: Mutex>>, join: Option>, exit: Arc, } @@ -64,7 +64,7 @@ impl Manager { /// Create a new filter manager that will dispatch decryption tasks onto /// the given thread pool. pub fn new() -> ::std::io::Result { - let (tx, rx) = mpsc::channel::>(); + let (tx, rx) = mpsc::channel::>(); let exit = Arc::new(AtomicBool::new(false)); let e = exit.clone();