Fix warnings: dyn

This commit is contained in:
adria0 2020-07-29 10:36:15 +02:00 committed by Artem Vorotnikov
parent 4adb44155d
commit 1700873f48
No known key found for this signature in database
GPG Key ID: E0148C3F2FBB7A20
198 changed files with 1180 additions and 1072 deletions

View File

@ -164,7 +164,7 @@ fn main() {
} }
} }
fn key_dir(location: &str, password: Option<Password>) -> Result<Box<KeyDirectory>, Error> { fn key_dir(location: &str, password: Option<Password>) -> Result<Box<dyn KeyDirectory>, Error> {
let dir: RootDiskDirectory = match location { let dir: RootDiskDirectory = match location {
"geth" => RootDiskDirectory::create(dir::geth(false))?, "geth" => RootDiskDirectory::create(dir::geth(false))?,
"geth-test" => RootDiskDirectory::create(dir::geth(true))?, "geth-test" => RootDiskDirectory::create(dir::geth(true))?,

View File

@ -335,7 +335,7 @@ where
Some(&self.path) Some(&self.path)
} }
fn as_vault_provider(&self) -> Option<&VaultKeyDirectoryProvider> { fn as_vault_provider(&self) -> Option<&dyn VaultKeyDirectoryProvider> {
Some(self) Some(self)
} }
@ -348,12 +348,12 @@ impl<T> VaultKeyDirectoryProvider for DiskDirectory<T>
where where
T: KeyFileManager, T: KeyFileManager,
{ {
fn create(&self, name: &str, key: VaultKey) -> Result<Box<VaultKeyDirectory>, Error> { fn create(&self, name: &str, key: VaultKey) -> Result<Box<dyn VaultKeyDirectory>, Error> {
let vault_dir = VaultDiskDirectory::create(&self.path, name, key)?; let vault_dir = VaultDiskDirectory::create(&self.path, name, key)?;
Ok(Box::new(vault_dir)) Ok(Box::new(vault_dir))
} }
fn open(&self, name: &str, key: VaultKey) -> Result<Box<VaultKeyDirectory>, Error> { fn open(&self, name: &str, key: VaultKey) -> Result<Box<dyn VaultKeyDirectory>, Error> {
let vault_dir = VaultDiskDirectory::at(&self.path, name, key)?; let vault_dir = VaultDiskDirectory::at(&self.path, name, key)?;
Ok(Box::new(vault_dir)) Ok(Box::new(vault_dir))
} }

View File

@ -60,7 +60,7 @@ pub trait KeyDirectory: Send + Sync {
None None
} }
/// Return vault provider, if available /// Return vault provider, if available
fn as_vault_provider(&self) -> Option<&VaultKeyDirectoryProvider> { fn as_vault_provider(&self) -> Option<&dyn VaultKeyDirectoryProvider> {
None None
} }
/// Unique representation of directory account collection /// Unique representation of directory account collection
@ -70,9 +70,9 @@ pub trait KeyDirectory: Send + Sync {
/// Vaults provider /// Vaults provider
pub trait VaultKeyDirectoryProvider { pub trait VaultKeyDirectoryProvider {
/// Create new vault with given key /// Create new vault with given key
fn create(&self, name: &str, key: VaultKey) -> Result<Box<VaultKeyDirectory>, Error>; fn create(&self, name: &str, key: VaultKey) -> Result<Box<dyn VaultKeyDirectory>, Error>;
/// Open existing vault with given key /// Open existing vault with given key
fn open(&self, name: &str, key: VaultKey) -> Result<Box<VaultKeyDirectory>, Error>; fn open(&self, name: &str, key: VaultKey) -> Result<Box<dyn VaultKeyDirectory>, Error>;
/// List all vaults /// List all vaults
fn list_vaults(&self) -> Result<Vec<String>, Error>; fn list_vaults(&self) -> Result<Vec<String>, Error>;
/// Get vault meta /// Get vault meta
@ -82,7 +82,7 @@ pub trait VaultKeyDirectoryProvider {
/// Vault directory /// Vault directory
pub trait VaultKeyDirectory: KeyDirectory { pub trait VaultKeyDirectory: KeyDirectory {
/// Cast to `KeyDirectory` /// Cast to `KeyDirectory`
fn as_key_directory(&self) -> &KeyDirectory; fn as_key_directory(&self) -> &dyn KeyDirectory;
/// Vault name /// Vault name
fn name(&self) -> &str; fn name(&self) -> &str;
/// Get vault key /// Get vault key

View File

@ -146,7 +146,7 @@ impl VaultDiskDirectory {
} }
impl VaultKeyDirectory for VaultDiskDirectory { impl VaultKeyDirectory for VaultDiskDirectory {
fn as_key_directory(&self) -> &KeyDirectory { fn as_key_directory(&self) -> &dyn KeyDirectory {
self self
} }

View File

@ -52,13 +52,13 @@ pub struct EthStore {
impl EthStore { impl EthStore {
/// Open a new accounts store with given key directory backend. /// Open a new accounts store with given key directory backend.
pub fn open(directory: Box<KeyDirectory>) -> Result<Self, Error> { pub fn open(directory: Box<dyn KeyDirectory>) -> Result<Self, Error> {
Self::open_with_iterations(directory, *KEY_ITERATIONS) Self::open_with_iterations(directory, *KEY_ITERATIONS)
} }
/// Open a new account store with given key directory backend and custom number of iterations. /// Open a new account store with given key directory backend and custom number of iterations.
pub fn open_with_iterations( pub fn open_with_iterations(
directory: Box<KeyDirectory>, directory: Box<dyn KeyDirectory>,
iterations: NonZeroU32, iterations: NonZeroU32,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
Ok(EthStore { Ok(EthStore {
@ -278,7 +278,7 @@ impl SecretStore for EthStore {
fn copy_account( fn copy_account(
&self, &self,
new_store: &SimpleSecretStore, new_store: &dyn SimpleSecretStore,
new_vault: SecretVaultRef, new_vault: SecretVaultRef,
account: &StoreAccountRef, account: &StoreAccountRef,
password: &Password, 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` /// Similar to `EthStore` but may store many accounts (with different passwords) for the same `Address`
pub struct EthMultiStore { pub struct EthMultiStore {
dir: Box<KeyDirectory>, dir: Box<dyn KeyDirectory>,
iterations: NonZeroU32, iterations: NonZeroU32,
// order lock: cache, then vaults // order lock: cache, then vaults
cache: RwLock<BTreeMap<StoreAccountRef, Vec<SafeAccount>>>, cache: RwLock<BTreeMap<StoreAccountRef, Vec<SafeAccount>>>,
vaults: Mutex<HashMap<String, Box<VaultKeyDirectory>>>, vaults: Mutex<HashMap<String, Box<dyn VaultKeyDirectory>>>,
timestamp: Mutex<Timestamp>, timestamp: Mutex<Timestamp>,
} }
@ -383,13 +383,13 @@ struct Timestamp {
impl EthMultiStore { impl EthMultiStore {
/// Open new multi-accounts store with given key directory backend. /// Open new multi-accounts store with given key directory backend.
pub fn open(directory: Box<KeyDirectory>) -> Result<Self, Error> { pub fn open(directory: Box<dyn KeyDirectory>) -> Result<Self, Error> {
Self::open_with_iterations(directory, *KEY_ITERATIONS) 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. /// Open new multi-accounts store with given key directory backend and custom number of iterations for new keys.
pub fn open_with_iterations( pub fn open_with_iterations(
directory: Box<KeyDirectory>, directory: Box<dyn KeyDirectory>,
iterations: NonZeroU32, iterations: NonZeroU32,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
let store = EthMultiStore { let store = EthMultiStore {
@ -953,7 +953,7 @@ mod tests {
} }
struct RootDiskDirectoryGuard { struct RootDiskDirectoryGuard {
pub key_dir: Option<Box<KeyDirectory>>, pub key_dir: Option<Box<dyn KeyDirectory>>,
_path: TempDir, _path: TempDir,
} }

View File

@ -22,7 +22,7 @@ use ethkey::Address;
use Error; use Error;
/// Import an account from a file. /// Import an account from a file.
pub fn import_account(path: &Path, dst: &KeyDirectory) -> Result<Address, Error> { pub fn import_account(path: &Path, dst: &dyn KeyDirectory) -> Result<Address, Error> {
let key_manager = DiskKeyFileManager::default(); let key_manager = DiskKeyFileManager::default();
let existing_accounts = dst let existing_accounts = dst
.load()? .load()?
@ -45,7 +45,10 @@ pub fn import_account(path: &Path, dst: &KeyDirectory) -> Result<Address, Error>
} }
/// Import all accounts from one directory to the other. /// Import all accounts from one directory to the other.
pub fn import_accounts(src: &KeyDirectory, dst: &KeyDirectory) -> Result<Vec<Address>, Error> { pub fn import_accounts(
src: &dyn KeyDirectory,
dst: &dyn KeyDirectory,
) -> Result<Vec<Address>, Error> {
let accounts = src.load()?; let accounts = src.load()?;
let existing_accounts = dst let existing_accounts = dst
.load()? .load()?
@ -74,7 +77,7 @@ pub fn read_geth_accounts(testnet: bool) -> Vec<Address> {
/// Import specific `desired` accounts from the Geth keystore into `dst`. /// Import specific `desired` accounts from the Geth keystore into `dst`.
pub fn import_geth_accounts( pub fn import_geth_accounts(
dst: &KeyDirectory, dst: &dyn KeyDirectory,
desired: HashSet<Address>, desired: HashSet<Address>,
testnet: bool, testnet: bool,
) -> Result<Vec<Address>, Error> { ) -> Result<Vec<Address>, Error> {

View File

@ -195,7 +195,7 @@ pub trait SecretStore: SimpleSecretStore {
/// Copies account between stores and vaults. /// Copies account between stores and vaults.
fn copy_account( fn copy_account(
&self, &self,
new_store: &SimpleSecretStore, new_store: &dyn SimpleSecretStore,
new_vault: SecretVaultRef, new_vault: SecretVaultRef,
account: &StoreAccountRef, account: &StoreAccountRef,
password: &Password, password: &Password,

View File

@ -231,7 +231,7 @@ impl Manager {
&self, &self,
device: &hidapi::HidDevice, device: &hidapi::HidDevice,
msg_type: MessageType, msg_type: MessageType,
msg: &Message, msg: &dyn Message,
) -> Result<usize, Error> { ) -> Result<usize, Error> {
let msg_id = msg_type as u16; let msg_id = msg_type as u16;
let mut message = msg.write_to_bytes()?; let mut message = msg.write_to_bytes()?;

View File

@ -77,7 +77,7 @@ pub struct AccountProvider {
/// Address book. /// Address book.
address_book: RwLock<AddressBook>, address_book: RwLock<AddressBook>,
/// Accounts on disk /// Accounts on disk
sstore: Box<SecretStore>, sstore: Box<dyn SecretStore>,
/// Accounts unlocked with rolling tokens /// Accounts unlocked with rolling tokens
transient_sstore: EthMultiStore, transient_sstore: EthMultiStore,
/// Accounts in hardware wallets. /// Accounts in hardware wallets.
@ -96,7 +96,7 @@ fn transient_sstore() -> EthMultiStore {
impl AccountProvider { impl AccountProvider {
/// Creates new account provider. /// Creates new account provider.
pub fn new(sstore: Box<SecretStore>, settings: AccountProviderSettings) -> Self { pub fn new(sstore: Box<dyn SecretStore>, settings: AccountProviderSettings) -> Self {
let mut hardware_store = None; let mut hardware_store = None;
if settings.enable_hardware_wallets { if settings.enable_hardware_wallets {

View File

@ -36,7 +36,7 @@ extern crate log;
extern crate matches; extern crate matches;
/// Boxed future response. /// Boxed future response.
pub type BoxFuture<T, E> = Box<futures::Future<Item = T, Error = E> + Send>; pub type BoxFuture<T, E> = Box<dyn futures::Future<Item = T, Error = E> + Send>;
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {

View File

@ -68,7 +68,7 @@ use crate::{
/// Database backing `BlockChain`. /// Database backing `BlockChain`.
pub trait BlockChainDB: Send + Sync { pub trait BlockChainDB: Send + Sync {
/// Generic key value store. /// Generic key value store.
fn key_value(&self) -> &Arc<KeyValueDB>; fn key_value(&self) -> &Arc<dyn KeyValueDB>;
/// Header blooms database. /// Header blooms database.
fn blooms(&self) -> &blooms_db::Database; fn blooms(&self) -> &blooms_db::Database;
@ -96,7 +96,7 @@ pub trait BlockChainDB: Send + Sync {
/// predefined config. /// predefined config.
pub trait BlockChainDBHandler: Send + Sync { pub trait BlockChainDBHandler: Send + Sync {
/// Open the predefined key-value database. /// Open the predefined key-value database.
fn open(&self, path: &Path) -> io::Result<Arc<BlockChainDB>>; fn open(&self, path: &Path) -> io::Result<Arc<dyn BlockChainDB>>;
} }
/// Interface for querying blocks by hash and by number. /// Interface for querying blocks by hash and by number.
@ -262,7 +262,7 @@ pub struct BlockChain {
transaction_addresses: RwLock<HashMap<H256, TransactionAddress>>, transaction_addresses: RwLock<HashMap<H256, TransactionAddress>>,
block_receipts: RwLock<HashMap<H256, BlockReceipts>>, block_receipts: RwLock<HashMap<H256, BlockReceipts>>,
db: Arc<BlockChainDB>, db: Arc<dyn BlockChainDB>,
cache_man: Mutex<CacheManager<CacheId>>, cache_man: Mutex<CacheManager<CacheId>>,
@ -576,7 +576,7 @@ impl<'a> Iterator for AncestryWithMetadataIter<'a> {
/// Returns epoch transitions. /// Returns epoch transitions.
pub struct EpochTransitionIter<'a> { pub struct EpochTransitionIter<'a> {
chain: &'a BlockChain, chain: &'a BlockChain,
prefix_iter: Box<Iterator<Item = (Box<[u8]>, Box<[u8]>)> + 'a>, prefix_iter: Box<dyn Iterator<Item = (Box<[u8]>, Box<[u8]>)> + 'a>,
} }
impl<'a> Iterator for EpochTransitionIter<'a> { impl<'a> Iterator for EpochTransitionIter<'a> {
@ -621,7 +621,7 @@ impl<'a> Iterator for EpochTransitionIter<'a> {
impl BlockChain { impl BlockChain {
/// Create new instance of blockchain from given Genesis. /// Create new instance of blockchain from given Genesis.
pub fn new(config: Config, genesis: &[u8], db: Arc<BlockChainDB>) -> BlockChain { pub fn new(config: Config, genesis: &[u8], db: Arc<dyn BlockChainDB>) -> BlockChain {
// 400 is the average size of the key // 400 is the average size of the key
let cache_man = CacheManager::new(config.pref_cache_size, config.max_cache_size, 400); let cache_man = CacheManager::new(config.pref_cache_size, config.max_cache_size, 400);
@ -1934,11 +1934,11 @@ mod tests {
_trace_blooms_dir: TempDir, _trace_blooms_dir: TempDir,
blooms: blooms_db::Database, blooms: blooms_db::Database,
trace_blooms: blooms_db::Database, trace_blooms: blooms_db::Database,
key_value: Arc<KeyValueDB>, key_value: Arc<dyn KeyValueDB>,
} }
impl BlockChainDB for TestBlockChainDB { impl BlockChainDB for TestBlockChainDB {
fn key_value(&self) -> &Arc<KeyValueDB> { fn key_value(&self) -> &Arc<dyn KeyValueDB> {
&self.key_value &self.key_value
} }
@ -1952,7 +1952,7 @@ mod tests {
} }
/// Creates new test instance of `BlockChainDB` /// Creates new test instance of `BlockChainDB`
pub fn new_db() -> Arc<BlockChainDB> { pub fn new_db() -> Arc<dyn BlockChainDB> {
let blooms_dir = TempDir::new("").unwrap(); let blooms_dir = TempDir::new("").unwrap();
let trace_blooms_dir = TempDir::new("").unwrap(); let trace_blooms_dir = TempDir::new("").unwrap();
@ -1967,12 +1967,12 @@ mod tests {
Arc::new(db) Arc::new(db)
} }
fn new_chain(genesis: encoded::Block, db: Arc<BlockChainDB>) -> BlockChain { fn new_chain(genesis: encoded::Block, db: Arc<dyn BlockChainDB>) -> BlockChain {
BlockChain::new(Config::default(), genesis.raw(), db) BlockChain::new(Config::default(), genesis.raw(), db)
} }
fn insert_block( fn insert_block(
db: &Arc<BlockChainDB>, db: &Arc<dyn BlockChainDB>,
bc: &BlockChain, bc: &BlockChain,
block: encoded::Block, block: encoded::Block,
receipts: Vec<Receipt>, receipts: Vec<Receipt>,
@ -1981,7 +1981,7 @@ mod tests {
} }
fn insert_block_commit( fn insert_block_commit(
db: &Arc<BlockChainDB>, db: &Arc<dyn BlockChainDB>,
bc: &BlockChain, bc: &BlockChain,
block: encoded::Block, block: encoded::Block,
receipts: Vec<Receipt>, receipts: Vec<Receipt>,

View File

@ -92,13 +92,13 @@ pub trait Key<T> {
/// Should be used to write value into database. /// Should be used to write value into database.
pub trait Writable { pub trait Writable {
/// Writes the value into the database. /// Writes the value into the database.
fn write<T, R>(&mut self, col: Option<u32>, key: &Key<T, Target = R>, value: &T) fn write<T, R>(&mut self, col: Option<u32>, key: &dyn Key<T, Target = R>, value: &T)
where where
T: rlp::Encodable, T: rlp::Encodable,
R: Deref<Target = [u8]>; R: Deref<Target = [u8]>;
/// Deletes key from the databse. /// Deletes key from the databse.
fn delete<T, R>(&mut self, col: Option<u32>, key: &Key<T, Target = R>) fn delete<T, R>(&mut self, col: Option<u32>, key: &dyn Key<T, Target = R>)
where where
T: rlp::Encodable, T: rlp::Encodable,
R: Deref<Target = [u8]>; R: Deref<Target = [u8]>;
@ -107,7 +107,7 @@ pub trait Writable {
fn write_with_cache<K, T, R>( fn write_with_cache<K, T, R>(
&mut self, &mut self,
col: Option<u32>, col: Option<u32>,
cache: &mut Cache<K, T>, cache: &mut dyn Cache<K, T>,
key: K, key: K,
value: T, value: T,
policy: CacheUpdatePolicy, policy: CacheUpdatePolicy,
@ -131,7 +131,7 @@ pub trait Writable {
fn extend_with_cache<K, T, R>( fn extend_with_cache<K, T, R>(
&mut self, &mut self,
col: Option<u32>, col: Option<u32>,
cache: &mut Cache<K, T>, cache: &mut dyn Cache<K, T>,
values: HashMap<K, T>, values: HashMap<K, T>,
policy: CacheUpdatePolicy, policy: CacheUpdatePolicy,
) where ) where
@ -159,7 +159,7 @@ pub trait Writable {
fn extend_with_option_cache<K, T, R>( fn extend_with_option_cache<K, T, R>(
&mut self, &mut self,
col: Option<u32>, col: Option<u32>,
cache: &mut Cache<K, Option<T>>, cache: &mut dyn Cache<K, Option<T>>,
values: HashMap<K, Option<T>>, values: HashMap<K, Option<T>>,
policy: CacheUpdatePolicy, policy: CacheUpdatePolicy,
) where ) where
@ -193,7 +193,7 @@ pub trait Writable {
/// Should be used to read values from database. /// Should be used to read values from database.
pub trait Readable { pub trait Readable {
/// Returns value for given key. /// Returns value for given key.
fn read<T, R>(&self, col: Option<u32>, key: &Key<T, Target = R>) -> Option<T> fn read<T, R>(&self, col: Option<u32>, key: &dyn Key<T, Target = R>) -> Option<T>
where where
T: rlp::Decodable, T: rlp::Decodable,
R: Deref<Target = [u8]>; R: Deref<Target = [u8]>;
@ -243,7 +243,7 @@ pub trait Readable {
} }
/// Returns true if given value exists. /// Returns true if given value exists.
fn exists<T, R>(&self, col: Option<u32>, key: &Key<T, Target = R>) -> bool fn exists<T, R>(&self, col: Option<u32>, key: &dyn Key<T, Target = R>) -> bool
where where
R: Deref<Target = [u8]>; R: Deref<Target = [u8]>;
@ -266,7 +266,7 @@ pub trait Readable {
} }
impl Writable for DBTransaction { impl Writable for DBTransaction {
fn write<T, R>(&mut self, col: Option<u32>, key: &Key<T, Target = R>, value: &T) fn write<T, R>(&mut self, col: Option<u32>, key: &dyn Key<T, Target = R>, value: &T)
where where
T: rlp::Encodable, T: rlp::Encodable,
R: Deref<Target = [u8]>, R: Deref<Target = [u8]>,
@ -274,7 +274,7 @@ impl Writable for DBTransaction {
self.put(col, &key.key(), &rlp::encode(value)); self.put(col, &key.key(), &rlp::encode(value));
} }
fn delete<T, R>(&mut self, col: Option<u32>, key: &Key<T, Target = R>) fn delete<T, R>(&mut self, col: Option<u32>, key: &dyn Key<T, Target = R>)
where where
T: rlp::Encodable, T: rlp::Encodable,
R: Deref<Target = [u8]>, R: Deref<Target = [u8]>,
@ -284,7 +284,7 @@ impl Writable for DBTransaction {
} }
impl<KVDB: KeyValueDB + ?Sized> Readable for KVDB { impl<KVDB: KeyValueDB + ?Sized> Readable for KVDB {
fn read<T, R>(&self, col: Option<u32>, key: &Key<T, Target = R>) -> Option<T> fn read<T, R>(&self, col: Option<u32>, key: &dyn Key<T, Target = R>) -> Option<T>
where where
T: rlp::Decodable, T: rlp::Decodable,
R: Deref<Target = [u8]>, R: Deref<Target = [u8]>,
@ -294,7 +294,7 @@ impl<KVDB: KeyValueDB + ?Sized> Readable for KVDB {
.map(|v| rlp::decode(&v).expect("decode db value failed")) .map(|v| rlp::decode(&v).expect("decode db value failed"))
} }
fn exists<T, R>(&self, col: Option<u32>, key: &Key<T, Target = R>) -> bool fn exists<T, R>(&self, col: Option<u32>, key: &dyn Key<T, Target = R>) -> bool
where where
R: Deref<Target = [u8]>, R: Deref<Target = [u8]>,
{ {

View File

@ -31,7 +31,7 @@ pub struct Factory {
impl Factory { impl Factory {
/// Create fresh instance of VM /// Create fresh instance of VM
/// Might choose implementation depending on supplied gas. /// Might choose implementation depending on supplied gas.
pub fn create(&self, params: ActionParams, schedule: &Schedule, depth: usize) -> Box<Exec> { pub fn create(&self, params: ActionParams, schedule: &Schedule, depth: usize) -> Box<dyn Exec> {
match self.evm { match self.evm {
VMType::Interpreter => { VMType::Interpreter => {
if Self::can_fit_in_usize(&params.gas) { if Self::can_fit_in_usize(&params.gas) {

View File

@ -112,10 +112,10 @@ impl<Gas: evm::CostType> Gasometer<Gas> {
/// it will be the amount of gas that the current context provides to the child context. /// it will be the amount of gas that the current context provides to the child context.
pub fn requirements( pub fn requirements(
&mut self, &mut self,
ext: &vm::Ext, ext: &dyn vm::Ext,
instruction: Instruction, instruction: Instruction,
info: &InstructionInfo, info: &InstructionInfo,
stack: &Stack<U256>, stack: &dyn Stack<U256>,
current_mem_size: usize, current_mem_size: usize,
) -> vm::Result<InstructionRequirements<Gas>> { ) -> vm::Result<InstructionRequirements<Gas>> {
let schedule = ext.schedule(); let schedule = ext.schedule();
@ -427,7 +427,7 @@ fn calculate_eip1283_sstore_gas<Gas: evm::CostType>(
} }
pub fn handle_eip1283_sstore_clears_refund( pub fn handle_eip1283_sstore_clears_refund(
ext: &mut vm::Ext, ext: &mut dyn vm::Ext,
original: &U256, original: &U256,
current: &U256, current: &U256,
new: &U256, new: &U256,

View File

@ -96,7 +96,7 @@ mod inner {
instruction: Instruction, instruction: Instruction,
info: &InstructionInfo, info: &InstructionInfo,
current_gas: &Cost, current_gas: &Cost,
stack: &Stack<U256>, stack: &dyn Stack<U256>,
) { ) {
let time = self.last_instruction.elapsed(); let time = self.last_instruction.elapsed();
self.last_instruction = Instant::now(); self.last_instruction = Instant::now();

View File

@ -136,7 +136,7 @@ mod tests {
#[test] #[test]
fn test_memory_read_and_write() { fn test_memory_read_and_write() {
// given // given
let mem: &mut Memory = &mut vec![]; let mem: &mut dyn Memory = &mut vec![];
mem.resize(0x80 + 32); mem.resize(0x80 + 32);
// when // when
@ -149,7 +149,7 @@ mod tests {
#[test] #[test]
fn test_memory_read_and_write_byte() { fn test_memory_read_and_write_byte() {
// given // given
let mem: &mut Memory = &mut vec![]; let mem: &mut dyn Memory = &mut vec![];
mem.resize(32); mem.resize(32);
// when // when
@ -163,7 +163,7 @@ mod tests {
#[test] #[test]
fn test_memory_read_slice_and_write_slice() { fn test_memory_read_slice_and_write_slice() {
let mem: &mut Memory = &mut vec![]; let mem: &mut dyn Memory = &mut vec![];
mem.resize(32); mem.resize(32);
{ {

View File

@ -192,7 +192,7 @@ pub struct Interpreter<Cost: CostType> {
} }
impl<Cost: 'static + CostType> vm::Exec for Interpreter<Cost> { impl<Cost: 'static + CostType> vm::Exec for Interpreter<Cost> {
fn exec(mut self: Box<Self>, ext: &mut vm::Ext) -> vm::ExecTrapResult<GasLeft> { fn exec(mut self: Box<Self>, ext: &mut dyn vm::Ext) -> vm::ExecTrapResult<GasLeft> {
loop { loop {
let result = self.step(ext); let result = self.step(ext);
match result { match result {
@ -213,7 +213,7 @@ impl<Cost: 'static + CostType> vm::Exec for Interpreter<Cost> {
} }
impl<Cost: 'static + CostType> vm::ResumeCall for Interpreter<Cost> { impl<Cost: 'static + CostType> vm::ResumeCall for Interpreter<Cost> {
fn resume_call(mut self: Box<Self>, result: MessageCallResult) -> Box<vm::Exec> { fn resume_call(mut self: Box<Self>, result: MessageCallResult) -> Box<dyn vm::Exec> {
{ {
let this = &mut *self; let this = &mut *self;
let (out_off, out_size) = this.resume_output_range.take().expect("Box<ResumeCall> is obtained from a call opcode; resume_output_range is always set after those opcodes are executed; qed"); let (out_off, out_size) = this.resume_output_range.take().expect("Box<ResumeCall> is obtained from a call opcode; resume_output_range is always set after those opcodes are executed; qed");
@ -254,7 +254,7 @@ impl<Cost: 'static + CostType> vm::ResumeCall for Interpreter<Cost> {
} }
impl<Cost: 'static + CostType> vm::ResumeCreate for Interpreter<Cost> { impl<Cost: 'static + CostType> vm::ResumeCreate for Interpreter<Cost> {
fn resume_create(mut self: Box<Self>, result: ContractCreateResult) -> Box<vm::Exec> { fn resume_create(mut self: Box<Self>, result: ContractCreateResult) -> Box<dyn vm::Exec> {
match result { match result {
ContractCreateResult::Created(address, gas_left) => { ContractCreateResult::Created(address, gas_left) => {
self.stack.push(address_to_u256(address)); self.stack.push(address_to_u256(address));
@ -318,7 +318,7 @@ impl<Cost: CostType> Interpreter<Cost> {
/// Execute a single step on the VM. /// Execute a single step on the VM.
#[inline(always)] #[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 { if self.done {
return InterpreterResult::Stopped; return InterpreterResult::Stopped;
} }
@ -531,7 +531,7 @@ impl<Cost: CostType> Interpreter<Cost> {
fn verify_instruction( fn verify_instruction(
&self, &self,
ext: &vm::Ext, ext: &dyn vm::Ext,
instruction: Instruction, instruction: Instruction,
info: &InstructionInfo, info: &InstructionInfo,
) -> vm::Result<()> { ) -> vm::Result<()> {
@ -574,7 +574,7 @@ impl<Cost: CostType> Interpreter<Cost> {
} }
} }
fn mem_written(instruction: Instruction, stack: &Stack<U256>) -> Option<(usize, usize)> { fn mem_written(instruction: Instruction, stack: &dyn Stack<U256>) -> Option<(usize, usize)> {
let read = |pos| stack.peek(pos).low_u64() as usize; let read = |pos| stack.peek(pos).low_u64() as usize;
let written = match instruction { let written = match instruction {
instructions::MSTORE | instructions::MLOAD => Some((read(0), 32)), instructions::MSTORE | instructions::MLOAD => Some((read(0), 32)),
@ -594,7 +594,7 @@ impl<Cost: CostType> Interpreter<Cost> {
} }
} }
fn store_written(instruction: Instruction, stack: &Stack<U256>) -> Option<(U256, U256)> { fn store_written(instruction: Instruction, stack: &dyn Stack<U256>) -> Option<(U256, U256)> {
match instruction { match instruction {
instructions::SSTORE => Some((stack.peek(0).clone(), stack.peek(1).clone())), instructions::SSTORE => Some((stack.peek(0).clone(), stack.peek(1).clone())),
_ => None, _ => None,
@ -604,7 +604,7 @@ impl<Cost: CostType> Interpreter<Cost> {
fn exec_instruction( fn exec_instruction(
&mut self, &mut self,
gas: Cost, gas: Cost,
ext: &mut vm::Ext, ext: &mut dyn vm::Ext,
instruction: Instruction, instruction: Instruction,
provided: Option<Cost>, provided: Option<Cost>,
) -> vm::Result<InstructionResult<Cost>> { ) -> vm::Result<InstructionResult<Cost>> {
@ -1374,7 +1374,7 @@ impl<Cost: CostType> Interpreter<Cost> {
Ok(InstructionResult::Ok) Ok(InstructionResult::Ok)
} }
fn copy_data_to_memory(mem: &mut Vec<u8>, stack: &mut Stack<U256>, source: &[u8]) { fn copy_data_to_memory(mem: &mut Vec<u8>, stack: &mut dyn Stack<U256>, source: &[u8]) {
let dest_offset = stack.pop_back(); let dest_offset = stack.pop_back();
let source_offset = stack.pop_back(); let source_offset = stack.pop_back();
let size = stack.pop_back(); let size = stack.pop_back();
@ -1462,7 +1462,7 @@ mod tests {
}; };
use vmtype::VMType; use vmtype::VMType;
fn interpreter(params: ActionParams, ext: &vm::Ext) -> Box<Exec> { fn interpreter(params: ActionParams, ext: &dyn vm::Ext) -> Box<dyn Exec> {
Factory::new(VMType::Interpreter, 1).create(params, ext.schedule(), ext.depth()) Factory::new(VMType::Interpreter, 1).create(params, ext.schedule(), ext.depth())
} }

View File

@ -82,7 +82,7 @@ impl<DB: HashDB<KeccakHasher, DBValue>> CHT<DB> {
} }
let mut recorder = Recorder::with_depth(from_level); 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)?; let t = TrieDB::new(&db, &self.root)?;
t.get_with(&key!(num), &mut recorder)?; t.get_with(&key!(num), &mut recorder)?;

View File

@ -48,8 +48,8 @@ pub trait ChainDataFetcher: Send + Sync + 'static {
fn epoch_transition( fn epoch_transition(
&self, &self,
_hash: H256, _hash: H256,
_engine: Arc<EthEngine>, _engine: Arc<dyn EthEngine>,
_checker: Arc<StateDependentProof<EthereumMachine>>, _checker: Arc<dyn StateDependentProof<EthereumMachine>>,
) -> Self::Transition; ) -> Self::Transition;
} }
@ -79,8 +79,8 @@ impl ChainDataFetcher for Unavailable {
fn epoch_transition( fn epoch_transition(
&self, &self,
_hash: H256, _hash: H256,
_engine: Arc<EthEngine>, _engine: Arc<dyn EthEngine>,
_checker: Arc<StateDependentProof<EthereumMachine>>, _checker: Arc<dyn StateDependentProof<EthereumMachine>>,
) -> Self::Transition { ) -> Self::Transition {
Err("fetching epoch transition proofs unavailable") Err("fetching epoch transition proofs unavailable")
} }

View File

@ -202,7 +202,7 @@ pub struct HeaderChain {
candidates: RwLock<BTreeMap<u64, Entry>>, candidates: RwLock<BTreeMap<u64, Entry>>,
best_block: RwLock<BlockDescriptor>, best_block: RwLock<BlockDescriptor>,
live_epoch_proofs: RwLock<H256FastMap<EpochTransition>>, live_epoch_proofs: RwLock<H256FastMap<EpochTransition>>,
db: Arc<KeyValueDB>, db: Arc<dyn KeyValueDB>,
col: Option<u32>, col: Option<u32>,
cache: Arc<Mutex<Cache>>, cache: Arc<Mutex<Cache>>,
} }
@ -210,7 +210,7 @@ pub struct HeaderChain {
impl HeaderChain { impl HeaderChain {
/// Create a new header chain given this genesis block and database to read from. /// Create a new header chain given this genesis block and database to read from.
pub fn new( pub fn new(
db: Arc<KeyValueDB>, db: Arc<dyn KeyValueDB>,
col: Option<u32>, col: Option<u32>,
spec: &Spec, spec: &Spec,
cache: Arc<Mutex<Cache>>, cache: Arc<Mutex<Cache>>,
@ -955,7 +955,7 @@ mod tests {
use parking_lot::Mutex; use parking_lot::Mutex;
use std::time::Duration; use std::time::Duration;
fn make_db() -> Arc<KeyValueDB> { fn make_db() -> Arc<dyn KeyValueDB> {
Arc::new(kvdb_memorydb::create(0)) Arc::new(kvdb_memorydb::create(0))
} }

View File

@ -81,7 +81,7 @@ impl Default for Config {
/// Trait for interacting with the header chain abstractly. /// Trait for interacting with the header chain abstractly.
pub trait LightChainClient: Send + Sync { pub trait LightChainClient: Send + Sync {
/// Adds a new `LightChainNotify` listener. /// Adds a new `LightChainNotify` listener.
fn add_listener(&self, listener: Weak<LightChainNotify>); fn add_listener(&self, listener: Weak<dyn LightChainNotify>);
/// Get chain info. /// Get chain info.
fn chain_info(&self) -> BlockChainInfo; fn chain_info(&self) -> BlockChainInfo;
@ -103,7 +103,10 @@ pub trait LightChainClient: Send + Sync {
fn score(&self, id: BlockId) -> Option<U256>; fn score(&self, id: BlockId) -> Option<U256>;
/// Get an iterator over a block and its ancestry. /// Get an iterator over a block and its ancestry.
fn ancestry_iter<'a>(&'a self, start: BlockId) -> Box<Iterator<Item = encoded::Header> + 'a>; fn ancestry_iter<'a>(
&'a self,
start: BlockId,
) -> Box<dyn Iterator<Item = encoded::Header> + 'a>;
/// Get the signing chain ID. /// Get the signing chain ID.
fn signing_chain_id(&self) -> Option<u64>; fn signing_chain_id(&self) -> Option<u64>;
@ -113,7 +116,7 @@ pub trait LightChainClient: Send + Sync {
fn env_info(&self, id: BlockId) -> Option<EnvInfo>; fn env_info(&self, id: BlockId) -> Option<EnvInfo>;
/// Get a handle to the consensus engine. /// Get a handle to the consensus engine.
fn engine(&self) -> &Arc<EthEngine>; fn engine(&self) -> &Arc<dyn EthEngine>;
/// Query whether a block is known. /// Query whether a block is known.
fn is_known(&self, hash: &H256) -> bool; fn is_known(&self, hash: &H256) -> bool;
@ -163,23 +166,23 @@ impl<T: LightChainClient> AsLightClient for T {
/// Light client implementation. /// Light client implementation.
pub struct Client<T> { pub struct Client<T> {
queue: HeaderQueue, queue: HeaderQueue,
engine: Arc<EthEngine>, engine: Arc<dyn EthEngine>,
chain: HeaderChain, chain: HeaderChain,
report: RwLock<ClientReport>, report: RwLock<ClientReport>,
import_lock: Mutex<()>, import_lock: Mutex<()>,
db: Arc<KeyValueDB>, db: Arc<dyn KeyValueDB>,
listeners: RwLock<Vec<Weak<LightChainNotify>>>, listeners: RwLock<Vec<Weak<dyn LightChainNotify>>>,
fetcher: T, fetcher: T,
verify_full: bool, verify_full: bool,
/// A closure to call when we want to restart the client /// A closure to call when we want to restart the client
exit_handler: Mutex<Option<Box<Fn(String) + 'static + Send>>>, exit_handler: Mutex<Option<Box<dyn Fn(String) + 'static + Send>>>,
} }
impl<T: ChainDataFetcher> Client<T> { impl<T: ChainDataFetcher> Client<T> {
/// Create a new `Client`. /// Create a new `Client`.
pub fn new( pub fn new(
config: Config, config: Config,
db: Arc<KeyValueDB>, db: Arc<dyn KeyValueDB>,
chain_col: Option<u32>, chain_col: Option<u32>,
spec: &Spec, spec: &Spec,
fetcher: T, fetcher: T,
@ -221,7 +224,7 @@ impl<T: ChainDataFetcher> Client<T> {
} }
/// Adds a new `LightChainNotify` listener. /// Adds a new `LightChainNotify` listener.
pub fn add_listener(&self, listener: Weak<LightChainNotify>) { pub fn add_listener(&self, listener: Weak<dyn LightChainNotify>) {
self.listeners.write().push(listener); self.listeners.write().push(listener);
} }
@ -398,7 +401,7 @@ impl<T: ChainDataFetcher> Client<T> {
} }
/// Get a handle to the verification engine. /// Get a handle to the verification engine.
pub fn engine(&self) -> &Arc<EthEngine> { pub fn engine(&self) -> &Arc<dyn EthEngine> {
&self.engine &self.engine
} }
@ -439,7 +442,7 @@ impl<T: ChainDataFetcher> Client<T> {
Arc::new(v) Arc::new(v)
} }
fn notify<F: Fn(&LightChainNotify)>(&self, f: F) { fn notify<F: Fn(&dyn LightChainNotify)>(&self, f: F) {
for listener in &*self.listeners.read() { for listener in &*self.listeners.read() {
if let Some(listener) = listener.upgrade() { if let Some(listener) = listener.upgrade() {
f(&*listener) f(&*listener)
@ -567,7 +570,7 @@ impl<T: ChainDataFetcher> Client<T> {
} }
impl<T: ChainDataFetcher> LightChainClient for Client<T> { impl<T: ChainDataFetcher> LightChainClient for Client<T> {
fn add_listener(&self, listener: Weak<LightChainNotify>) { fn add_listener(&self, listener: Weak<dyn LightChainNotify>) {
Client::add_listener(self, listener) Client::add_listener(self, listener)
} }
@ -595,7 +598,10 @@ impl<T: ChainDataFetcher> LightChainClient for Client<T> {
Client::score(self, id) Client::score(self, id)
} }
fn ancestry_iter<'a>(&'a self, start: BlockId) -> Box<Iterator<Item = encoded::Header> + 'a> { fn ancestry_iter<'a>(
&'a self,
start: BlockId,
) -> Box<dyn Iterator<Item = encoded::Header> + 'a> {
Box::new(Client::ancestry_iter(self, start)) Box::new(Client::ancestry_iter(self, start))
} }
@ -607,7 +613,7 @@ impl<T: ChainDataFetcher> LightChainClient for Client<T> {
Client::env_info(self, id) Client::env_info(self, id)
} }
fn engine(&self) -> &Arc<EthEngine> { fn engine(&self) -> &Arc<dyn EthEngine> {
Client::engine(self) Client::engine(self)
} }
@ -668,7 +674,7 @@ impl<T: ChainDataFetcher> ::ethcore::client::EngineClient for Client<T> {
}) })
} }
fn as_full_client(&self) -> Option<&::ethcore::client::BlockChainClient> { fn as_full_client(&self) -> Option<&dyn crate::ethcore::client::BlockChainClient> {
None None
} }

View File

@ -66,7 +66,7 @@ impl<T: ChainDataFetcher> Service<T> {
config: ClientConfig, config: ClientConfig,
spec: &Spec, spec: &Spec,
fetcher: T, fetcher: T,
db: Arc<BlockChainDB>, db: Arc<dyn BlockChainDB>,
cache: Arc<Mutex<Cache>>, cache: Arc<Mutex<Cache>>,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
let io_service = IoService::<ClientIoMessage>::start().map_err(Error::Io)?; let io_service = IoService::<ClientIoMessage>::start().map_err(Error::Io)?;
@ -89,14 +89,14 @@ impl<T: ChainDataFetcher> Service<T> {
} }
/// Set the actor to be notified on certain chain events /// Set the actor to be notified on certain chain events
pub fn add_notify(&self, notify: Arc<LightChainNotify>) { pub fn add_notify(&self, notify: Arc<dyn LightChainNotify>) {
self.client.add_listener(Arc::downgrade(&notify)); self.client.add_listener(Arc::downgrade(&notify));
} }
/// Register an I/O handler on the service. /// Register an I/O handler on the service.
pub fn register_handler( pub fn register_handler(
&self, &self,
handler: Arc<IoHandler<ClientIoMessage> + Send>, handler: Arc<dyn IoHandler<ClientIoMessage> + Send>,
) -> Result<(), IoError> { ) -> Result<(), IoError> {
self.io_service.register_handler(handler) self.io_service.register_handler(handler)
} }

View File

@ -118,13 +118,13 @@ pub trait EventContext: BasicContext {
fn peer(&self) -> PeerId; fn peer(&self) -> PeerId;
/// Treat the event context as a basic context. /// Treat the event context as a basic context.
fn as_basic(&self) -> &BasicContext; fn as_basic(&self) -> &dyn BasicContext;
} }
/// Basic context. /// Basic context.
pub struct TickCtx<'a> { pub struct TickCtx<'a> {
/// Io context to enable dispatch. /// Io context to enable dispatch.
pub io: &'a IoContext, pub io: &'a dyn IoContext,
/// Protocol implementation. /// Protocol implementation.
pub proto: &'a LightProtocol, pub proto: &'a LightProtocol,
} }
@ -155,7 +155,7 @@ impl<'a> BasicContext for TickCtx<'a> {
/// an io context. /// an io context.
pub struct Ctx<'a> { pub struct Ctx<'a> {
/// Io context to enable immediate response to events. /// Io context to enable immediate response to events.
pub io: &'a IoContext, pub io: &'a dyn IoContext,
/// Protocol implementation. /// Protocol implementation.
pub proto: &'a LightProtocol, pub proto: &'a LightProtocol,
/// Relevant peer for event. /// Relevant peer for event.
@ -189,7 +189,7 @@ impl<'a> EventContext for Ctx<'a> {
self.peer self.peer
} }
fn as_basic(&self) -> &BasicContext { fn as_basic(&self) -> &dyn BasicContext {
&*self &*self
} }
} }

View File

@ -89,7 +89,7 @@ pub struct LoadDistribution {
impl LoadDistribution { impl LoadDistribution {
/// Load rolling samples from the given store. /// 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(); let mut samples = store.load();
for kind_samples in samples.values_mut() { for kind_samples in samples.values_mut() {
@ -146,7 +146,7 @@ impl LoadDistribution {
} }
/// End the current time period. Provide a store to /// 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 active_period = self.active_period.read();
let mut samples = self.samples.write(); let mut samples = self.samples.write();

View File

@ -242,7 +242,7 @@ pub trait Handler: Send + Sync {
/// Called when a peer connects. /// Called when a peer connects.
fn on_connect( fn on_connect(
&self, &self,
_ctx: &EventContext, _ctx: &dyn EventContext,
_status: &Status, _status: &Status,
_capabilities: &Capabilities, _capabilities: &Capabilities,
) -> PeerStatus { ) -> PeerStatus {
@ -250,19 +250,25 @@ pub trait Handler: Send + Sync {
} }
/// Called when a peer disconnects, with a list of unfulfilled request IDs as /// Called when a peer disconnects, with a list of unfulfilled request IDs as
/// of yet. /// 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. /// 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. /// 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. /// Called when a peer responds to requests.
/// Responses not guaranteed to contain valid data and are not yet checked against /// Responses not guaranteed to contain valid data and are not yet checked against
/// the requests they correspond to. /// 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. /// 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. /// 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 /// Called on abort. This signals to handlers that they should clean up
/// and ignore peers. /// and ignore peers.
// TODO: coreresponding `on_activate`? // TODO: coreresponding `on_activate`?
@ -298,7 +304,7 @@ pub struct Params {
/// Initial capabilities. /// Initial capabilities.
pub capabilities: Capabilities, pub capabilities: Capabilities,
/// The sample store (`None` if data shouldn't persist between runs). /// The sample store (`None` if data shouldn't persist between runs).
pub sample_store: Option<Box<SampleStore>>, pub sample_store: Option<Box<dyn SampleStore>>,
} }
/// Type alias for convenience. /// Type alias for convenience.
@ -403,7 +409,7 @@ impl Statistics {
// Locks must be acquired in the order declared, and when holding a read lock // 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. // on the peers, only one peer may be held at a time.
pub struct LightProtocol { pub struct LightProtocol {
provider: Arc<Provider>, provider: Arc<dyn Provider>,
config: Config, config: Config,
genesis_hash: H256, genesis_hash: H256,
network_id: u64, network_id: u64,
@ -412,16 +418,16 @@ pub struct LightProtocol {
capabilities: RwLock<Capabilities>, capabilities: RwLock<Capabilities>,
flow_params: RwLock<Arc<FlowParams>>, flow_params: RwLock<Arc<FlowParams>>,
free_flow_params: Arc<FlowParams>, free_flow_params: Arc<FlowParams>,
handlers: Vec<Arc<Handler>>, handlers: Vec<Arc<dyn Handler>>,
req_id: AtomicUsize, req_id: AtomicUsize,
sample_store: Box<SampleStore>, sample_store: Box<dyn SampleStore>,
load_distribution: LoadDistribution, load_distribution: LoadDistribution,
statistics: RwLock<Statistics>, statistics: RwLock<Statistics>,
} }
impl LightProtocol { impl LightProtocol {
/// Create a new instance of the protocol manager. /// Create a new instance of the protocol manager.
pub fn new(provider: Arc<Provider>, params: Params) -> Self { pub fn new(provider: Arc<dyn Provider>, params: Params) -> Self {
debug!(target: "pip", "Initializing light protocol handler"); debug!(target: "pip", "Initializing light protocol handler");
let genesis_hash = provider.chain_info().genesis_hash; let genesis_hash = provider.chain_info().genesis_hash;
@ -494,7 +500,7 @@ impl LightProtocol {
/// with an event. /// with an event.
pub fn request_from( pub fn request_from(
&self, &self,
io: &IoContext, io: &dyn IoContext,
peer_id: PeerId, peer_id: PeerId,
requests: Requests, requests: Requests,
) -> Result<ReqId, Error> { ) -> Result<ReqId, Error> {
@ -543,7 +549,7 @@ impl LightProtocol {
/// Make an announcement of new chain head and capabilities to all peers. /// Make an announcement of new chain head and capabilities to all peers.
/// The announcement is expected to be valid. /// 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 mut reorgs_map = HashMap::new();
let now = Instant::now(); let now = Instant::now();
@ -598,7 +604,7 @@ impl LightProtocol {
/// These are intended to be added when the protocol structure /// These are intended to be added when the protocol structure
/// is initialized as a means of customizing its behavior, /// is initialized as a means of customizing its behavior,
/// and dispatching requests immediately upon events. /// and dispatching requests immediately upon events.
pub fn add_handler(&mut self, handler: Arc<Handler>) { pub fn add_handler(&mut self, handler: Arc<dyn Handler>) {
self.handlers.push(handler); self.handlers.push(handler);
} }
@ -667,7 +673,7 @@ impl LightProtocol {
/// Handle a packet using the given io context. /// Handle a packet using the given io context.
/// Packet data is _untrusted_, which means that invalid data won't lead to /// Packet data is _untrusted_, which means that invalid data won't lead to
/// issues. /// 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); let rlp = Rlp::new(data);
trace!(target: "pip", "Incoming packet {} from peer {}", packet_id, peer); trace!(target: "pip", "Incoming packet {} from peer {}", packet_id, peer);
@ -694,7 +700,7 @@ impl LightProtocol {
} }
// check timeouts and punish peers. // check timeouts and punish peers.
fn timeout_check(&self, io: &IoContext) { fn timeout_check(&self, io: &dyn IoContext) {
let now = Instant::now(); let now = Instant::now();
// handshake timeout // handshake timeout
@ -735,7 +741,7 @@ impl LightProtocol {
// propagate transactions to relay peers. // propagate transactions to relay peers.
// if we aren't on the mainnet, we just propagate to all 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 { if self.capabilities.read().tx_relay {
return; return;
} }
@ -785,7 +791,7 @@ impl LightProtocol {
} }
/// called when a peer connects. /// 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) { let proto_version = match io.protocol_version(peer).ok_or(Error::WrongNetwork) {
Ok(pv) => pv, Ok(pv) => pv,
Err(e) => { Err(e) => {
@ -837,7 +843,7 @@ impl LightProtocol {
} }
/// called when a peer disconnects. /// 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); trace!(target: "pip", "Peer {} disconnecting", peer);
self.pending_peers.write().remove(&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. /// Execute the given closure with a basic context derived from the I/O context.
pub fn with_context<F, T>(&self, io: &IoContext, f: F) -> T pub fn with_context<F, T>(&self, io: &dyn IoContext, f: F) -> T
where where
F: FnOnce(&BasicContext) -> T, F: FnOnce(&dyn BasicContext) -> T,
{ {
f(&TickCtx { io, proto: self }) f(&TickCtx { io, proto: self })
} }
fn tick_handlers(&self, io: &IoContext) { fn tick_handlers(&self, io: &dyn IoContext) {
for handler in &self.handlers { for handler in &self.handlers {
handler.tick(&TickCtx { io, proto: self }) 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); self.load_distribution.end_period(&*self.sample_store);
let avg_peer_count = self.statistics.read().avg_peer_count(); let avg_peer_count = self.statistics.read().avg_peer_count();
@ -920,7 +926,7 @@ impl LightProtocol {
impl LightProtocol { impl LightProtocol {
// Handle status message from peer. // 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) { let pending = match self.pending_peers.write().remove(&peer) {
Some(pending) => pending, Some(pending) => pending,
None => { None => {
@ -992,7 +998,7 @@ impl LightProtocol {
} }
// Handle an announcement. // 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) { if !self.peers.read().contains_key(&peer) {
debug!(target: "pip", "Ignoring announcement from unknown peer"); debug!(target: "pip", "Ignoring announcement from unknown peer");
return Ok(()); return Ok(());
@ -1040,7 +1046,7 @@ impl LightProtocol {
} }
// Receive requests from a peer. // 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. // the maximum amount of requests we'll fill in a single packet.
const MAX_REQUESTS: usize = 256; const MAX_REQUESTS: usize = 256;
@ -1134,7 +1140,7 @@ impl LightProtocol {
} }
// handle a packet with responses. // 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 (req_id, responses) = {
let id_guard = self.pre_verify_response(peer, &raw)?; let id_guard = self.pre_verify_response(peer, &raw)?;
let responses: Vec<Response> = raw.list_at(2)?; let responses: Vec<Response> = raw.list_at(2)?;
@ -1157,7 +1163,7 @@ impl LightProtocol {
} }
// handle an update of request credits parameters. // 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 peers = self.peers.read();
let peer = peers.get(&peer_id).ok_or(Error::UnknownPeer)?; let peer = peers.get(&peer_id).ok_or(Error::UnknownPeer)?;
@ -1196,7 +1202,7 @@ impl LightProtocol {
fn acknowledge_update( fn acknowledge_update(
&self, &self,
peer_id: PeerId, peer_id: PeerId,
_io: &IoContext, _io: &dyn IoContext,
_raw: &Rlp, _raw: &Rlp,
) -> Result<(), Error> { ) -> Result<(), Error> {
let peers = self.peers.read(); let peers = self.peers.read();
@ -1218,7 +1224,12 @@ impl LightProtocol {
} }
// Receive a set of transactions to relay. // 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; const MAX_TRANSACTIONS: usize = 256;
let txs: Vec<_> = data let txs: Vec<_> = data
@ -1245,7 +1256,7 @@ impl LightProtocol {
} }
// if something went wrong, figure out how much to punish the peer. // 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() { match e.punishment() {
Punishment::None => {} Punishment::None => {}
Punishment::Disconnect => { Punishment::Disconnect => {
@ -1260,7 +1271,7 @@ fn punish(peer: PeerId, io: &IoContext, e: &Error) {
} }
impl NetworkProtocolHandler for LightProtocol { impl NetworkProtocolHandler for LightProtocol {
fn initialize(&self, io: &NetworkContext) { fn initialize(&self, io: &dyn NetworkContext) {
io.register_timer(TIMEOUT, TIMEOUT_INTERVAL) io.register_timer(TIMEOUT, TIMEOUT_INTERVAL)
.expect("Error registering sync timer."); .expect("Error registering sync timer.");
io.register_timer(TICK_TIMEOUT, TICK_TIMEOUT_INTERVAL) io.register_timer(TICK_TIMEOUT, TICK_TIMEOUT_INTERVAL)
@ -1273,19 +1284,19 @@ impl NetworkProtocolHandler for LightProtocol {
.expect("Error registering statistics timer."); .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); 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); 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); self.on_disconnect(*peer, &io);
} }
fn timeout(&self, io: &NetworkContext, timer: TimerToken) { fn timeout(&self, io: &dyn NetworkContext, timer: TimerToken) {
match timer { match timer {
TIMEOUT => self.timeout_check(&io), TIMEOUT => self.timeout_check(&io),
TICK_TIMEOUT => self.tick_handlers(&io), TICK_TIMEOUT => self.tick_handlers(&io),

View File

@ -99,7 +99,7 @@ pub trait OnDemandRequester: Send + Sync {
/// Fails if back-reference are not coherent. /// Fails if back-reference are not coherent.
fn request<T>( fn request<T>(
&self, &self,
ctx: &BasicContext, ctx: &dyn BasicContext,
requests: T, requests: T,
) -> Result<OnResponses<T>, basic_request::NoSuchOutput> ) -> Result<OnResponses<T>, basic_request::NoSuchOutput>
where where
@ -111,7 +111,7 @@ pub trait OnDemandRequester: Send + Sync {
/// The returned vector of responses will correspond to the requests exactly. /// The returned vector of responses will correspond to the requests exactly.
fn request_raw( fn request_raw(
&self, &self,
ctx: &BasicContext, ctx: &dyn BasicContext,
requests: Vec<Request>, requests: Vec<Request>,
) -> Result<Receiver<PendingResponse>, basic_request::NoSuchOutput>; ) -> Result<Receiver<PendingResponse>, basic_request::NoSuchOutput>;
} }
@ -396,7 +396,7 @@ pub struct OnDemand {
impl OnDemandRequester for OnDemand { impl OnDemandRequester for OnDemand {
fn request_raw( fn request_raw(
&self, &self,
ctx: &BasicContext, ctx: &dyn BasicContext,
requests: Vec<Request>, requests: Vec<Request>,
) -> Result<Receiver<PendingResponse>, basic_request::NoSuchOutput> { ) -> Result<Receiver<PendingResponse>, basic_request::NoSuchOutput> {
let (sender, receiver) = oneshot::channel(); let (sender, receiver) = oneshot::channel();
@ -460,7 +460,7 @@ impl OnDemandRequester for OnDemand {
fn request<T>( fn request<T>(
&self, &self,
ctx: &BasicContext, ctx: &dyn BasicContext,
requests: T, requests: T,
) -> Result<OnResponses<T>, basic_request::NoSuchOutput> ) -> Result<OnResponses<T>, basic_request::NoSuchOutput>
where where
@ -543,7 +543,7 @@ impl OnDemand {
// maybe dispatch pending requests. // maybe dispatch pending requests.
// sometimes // sometimes
fn attempt_dispatch(&self, ctx: &BasicContext) { fn attempt_dispatch(&self, ctx: &dyn BasicContext) {
if !self.no_immediate_dispatch { if !self.no_immediate_dispatch {
self.dispatch_pending(ctx) self.dispatch_pending(ctx)
} }
@ -551,7 +551,7 @@ impl OnDemand {
// dispatch pending requests, and discard those for which the corresponding // dispatch pending requests, and discard those for which the corresponding
// receiver has been dropped. // receiver has been dropped.
fn dispatch_pending(&self, ctx: &BasicContext) { fn dispatch_pending(&self, ctx: &dyn BasicContext) {
if self.pending.read().is_empty() { if self.pending.read().is_empty() {
return; return;
} }
@ -606,7 +606,7 @@ impl OnDemand {
// submit a pending request set. attempts to answer from cache before // submit a pending request set. attempts to answer from cache before
// going to the network. if complete, sends response and consumes the struct. // 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 // answer as many requests from cache as we can, and schedule for dispatch
// if incomplete. // if incomplete.
@ -625,7 +625,7 @@ impl OnDemand {
impl Handler for OnDemand { impl Handler for OnDemand {
fn on_connect( fn on_connect(
&self, &self,
ctx: &EventContext, ctx: &dyn EventContext,
status: &Status, status: &Status,
capabilities: &Capabilities, capabilities: &Capabilities,
) -> PeerStatus { ) -> PeerStatus {
@ -640,7 +640,7 @@ impl Handler for OnDemand {
PeerStatus::Kept 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()); self.peers.write().remove(&ctx.peer());
let ctx = ctx.as_basic(); let ctx = ctx.as_basic();
@ -657,7 +657,7 @@ impl Handler for OnDemand {
self.attempt_dispatch(ctx); 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(); let mut peers = self.peers.write();
if let Some(ref mut peer) = peers.get_mut(&ctx.peer()) { if let Some(ref mut peer) = peers.get_mut(&ctx.peer()) {
@ -671,7 +671,7 @@ impl Handler for OnDemand {
fn on_responses( fn on_responses(
&self, &self,
ctx: &EventContext, ctx: &dyn EventContext,
req_id: ReqId, req_id: ReqId,
responses: &[basic_request::Response], responses: &[basic_request::Response],
) { ) {
@ -713,7 +713,7 @@ impl Handler for OnDemand {
self.submit_pending(ctx.as_basic(), pending); self.submit_pending(ctx.as_basic(), pending);
} }
fn tick(&self, ctx: &BasicContext) { fn tick(&self, ctx: &dyn BasicContext) {
self.attempt_dispatch(ctx) self.attempt_dispatch(ctx)
} }
} }

View File

@ -1117,7 +1117,7 @@ pub struct TransactionProof {
// TODO: it's not really possible to provide this if the header is unknown. // TODO: it's not really possible to provide this if the header is unknown.
pub env_info: EnvInfo, pub env_info: EnvInfo,
/// Consensus engine. /// Consensus engine.
pub engine: Arc<EthEngine>, pub engine: Arc<dyn EthEngine>,
} }
impl TransactionProof { impl TransactionProof {
@ -1164,9 +1164,9 @@ pub struct Signal {
/// Block hash and number to fetch proof for. /// Block hash and number to fetch proof for.
pub hash: H256, pub hash: H256,
/// Consensus engine, used to check the proof. /// Consensus engine, used to check the proof.
pub engine: Arc<EthEngine>, pub engine: Arc<dyn EthEngine>,
/// Special checker for the proof. /// Special checker for the proof.
pub proof_check: Arc<StateDependentProof<EthereumMachine>>, pub proof_check: Arc<dyn StateDependentProof<EthereumMachine>>,
} }
impl Signal { impl Signal {

View File

@ -51,7 +51,7 @@ impl EventContext for Context {
} }
} }
fn as_basic(&self) -> &BasicContext { fn as_basic(&self) -> &dyn BasicContext {
self self
} }
} }

View File

@ -129,7 +129,7 @@ pub enum ImportDestination {
Future, Future,
} }
type Listener = Box<Fn(&[H256]) + Send + Sync>; type Listener = Box<dyn Fn(&[H256]) + Send + Sync>;
/// Light transaction queue. See module docs for more details. /// Light transaction queue. See module docs for more details.
#[derive(Default)] #[derive(Default)]

View File

@ -49,13 +49,13 @@ use_contract!(peer_set, "res/peer_set.json");
/// Connection filter that uses a contract to manage permissions. /// Connection filter that uses a contract to manage permissions.
pub struct NodeFilter { pub struct NodeFilter {
client: Weak<BlockChainClient>, client: Weak<dyn BlockChainClient>,
contract_address: Address, contract_address: Address,
} }
impl NodeFilter { impl NodeFilter {
/// Create a new instance. Accepts a contract address. /// Create a new instance. Accepts a contract address.
pub fn new(client: Weak<BlockChainClient>, contract_address: Address) -> NodeFilter { pub fn new(client: Weak<dyn BlockChainClient>, contract_address: Address) -> NodeFilter {
NodeFilter { NodeFilter {
client, client,
contract_address, contract_address,
@ -127,7 +127,7 @@ mod test {
) )
.unwrap(); .unwrap();
let filter = NodeFilter::new( let filter = NodeFilter::new(
Arc::downgrade(&client) as Weak<BlockChainClient>, Arc::downgrade(&client) as Weak<dyn BlockChainClient>,
contract_addr, contract_addr,
); );
let self1: NodeId = "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002".into(); let self1: NodeId = "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002".into();

View File

@ -77,7 +77,7 @@ pub struct SecretStoreEncryptor {
config: EncryptorConfig, config: EncryptorConfig,
client: FetchClient, client: FetchClient,
sessions: Mutex<HashMap<Address, EncryptionSession>>, sessions: Mutex<HashMap<Address, EncryptionSession>>,
signer: Arc<Signer>, signer: Arc<dyn Signer>,
} }
impl SecretStoreEncryptor { impl SecretStoreEncryptor {
@ -85,7 +85,7 @@ impl SecretStoreEncryptor {
pub fn new( pub fn new(
config: EncryptorConfig, config: EncryptorConfig,
client: FetchClient, client: FetchClient,
signer: Arc<Signer>, signer: Arc<dyn Signer>,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
Ok(SecretStoreEncryptor { Ok(SecretStoreEncryptor {
config, config,

View File

@ -116,7 +116,7 @@ pub enum Error {
} }
impl error::Error for Error { impl error::Error for Error {
fn source(&self) -> Option<&(error::Error + 'static)> { fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self { match self {
Error::Io(e) => Some(e), Error::Io(e) => Some(e),
Error::Decoder(e) => Some(e), Error::Decoder(e) => Some(e),

View File

@ -198,17 +198,17 @@ impl Signer for KeyPairSigner {
/// Manager of private transactions /// Manager of private transactions
pub struct Provider { pub struct Provider {
encryptor: Box<Encryptor>, encryptor: Box<dyn Encryptor>,
validator_accounts: HashSet<Address>, validator_accounts: HashSet<Address>,
signer_account: Option<Address>, signer_account: Option<Address>,
notify: RwLock<Vec<Weak<ChainNotify>>>, notify: RwLock<Vec<Weak<dyn ChainNotify>>>,
transactions_for_signing: RwLock<SigningStore>, transactions_for_signing: RwLock<SigningStore>,
transactions_for_verification: VerificationStore, transactions_for_verification: VerificationStore,
client: Arc<Client>, client: Arc<Client>,
miner: Arc<Miner>, miner: Arc<Miner>,
accounts: Arc<Signer>, accounts: Arc<dyn Signer>,
channel: IoChannel<ClientIoMessage>, channel: IoChannel<ClientIoMessage>,
keys_provider: Arc<KeyProvider>, keys_provider: Arc<dyn KeyProvider>,
} }
#[derive(Debug)] #[derive(Debug)]
@ -228,11 +228,11 @@ impl Provider {
pub fn new( pub fn new(
client: Arc<Client>, client: Arc<Client>,
miner: Arc<Miner>, miner: Arc<Miner>,
accounts: Arc<Signer>, accounts: Arc<dyn Signer>,
encryptor: Box<Encryptor>, encryptor: Box<dyn Encryptor>,
config: ProviderConfig, config: ProviderConfig,
channel: IoChannel<ClientIoMessage>, channel: IoChannel<ClientIoMessage>,
keys_provider: Arc<KeyProvider>, keys_provider: Arc<dyn KeyProvider>,
) -> Self { ) -> Self {
keys_provider.update_acl_contract(); keys_provider.update_acl_contract();
Provider { Provider {
@ -253,13 +253,13 @@ impl Provider {
// TODO [ToDr] Don't use `ChainNotify` here! // TODO [ToDr] Don't use `ChainNotify` here!
// Better to create a separate notification type for this. // Better to create a separate notification type for this.
/// Adds an actor to be notified on certain events /// Adds an actor to be notified on certain events
pub fn add_notify(&self, target: Arc<ChainNotify>) { pub fn add_notify(&self, target: Arc<dyn ChainNotify>) {
self.notify.write().push(Arc::downgrade(&target)); self.notify.write().push(Arc::downgrade(&target));
} }
fn notify<F>(&self, f: F) fn notify<F>(&self, f: F)
where where
F: Fn(&ChainNotify), F: Fn(&dyn ChainNotify),
{ {
for np in self.notify.read().iter() { for np in self.notify.read().iter() {
if let Some(n) = np.upgrade() { if let Some(n) = np.upgrade() {

View File

@ -82,7 +82,7 @@ pub struct ClientService {
client: Arc<Client>, client: Arc<Client>,
snapshot: Arc<SnapshotService>, snapshot: Arc<SnapshotService>,
private_tx: Arc<PrivateTxService>, private_tx: Arc<PrivateTxService>,
database: Arc<BlockChainDB>, database: Arc<dyn BlockChainDB>,
_stop_guard: StopGuard, _stop_guard: StopGuard,
} }
@ -91,13 +91,13 @@ impl ClientService {
pub fn start( pub fn start(
config: ClientConfig, config: ClientConfig,
spec: &Spec, spec: &Spec,
blockchain_db: Arc<BlockChainDB>, blockchain_db: Arc<dyn BlockChainDB>,
snapshot_path: &Path, snapshot_path: &Path,
restoration_db_handler: Box<BlockChainDBHandler>, restoration_db_handler: Box<dyn BlockChainDBHandler>,
_ipc_path: &Path, _ipc_path: &Path,
miner: Arc<Miner>, miner: Arc<Miner>,
signer: Arc<Signer>, signer: Arc<dyn Signer>,
encryptor: Box<ethcore_private_tx::Encryptor>, encryptor: Box<dyn ethcore_private_tx::Encryptor>,
private_tx_conf: ethcore_private_tx::ProviderConfig, private_tx_conf: ethcore_private_tx::ProviderConfig,
private_encryptor_conf: ethcore_private_tx::EncryptorConfig, private_encryptor_conf: ethcore_private_tx::EncryptorConfig,
) -> Result<ClientService, Error> { ) -> Result<ClientService, Error> {
@ -169,7 +169,7 @@ impl ClientService {
/// Get general IO interface /// Get general IO interface
pub fn register_io_handler( pub fn register_io_handler(
&self, &self,
handler: Arc<IoHandler<ClientIoMessage> + Send>, handler: Arc<dyn IoHandler<ClientIoMessage> + Send>,
) -> Result<(), IoError> { ) -> Result<(), IoError> {
self.io_service.register_handler(handler) self.io_service.register_handler(handler)
} }
@ -195,12 +195,12 @@ impl ClientService {
} }
/// Set the actor to be notified on certain chain events /// Set the actor to be notified on certain chain events
pub fn add_notify(&self, notify: Arc<ChainNotify>) { pub fn add_notify(&self, notify: Arc<dyn ChainNotify>) {
self.client.add_notify(notify); self.client.add_notify(notify);
} }
/// Get a handle to the database. /// Get a handle to the database.
pub fn db(&self) -> Arc<BlockChainDB> { pub fn db(&self) -> Arc<dyn BlockChainDB> {
self.database.clone() self.database.clone()
} }

View File

@ -61,9 +61,9 @@ impl Factory {
/// This will panic when write operations are called. /// This will panic when write operations are called.
pub fn readonly<'db>( pub fn readonly<'db>(
&self, &self,
db: &'db HashDB<KeccakHasher, DBValue>, db: &'db dyn HashDB<KeccakHasher, DBValue>,
address_hash: H256, address_hash: H256,
) -> Box<HashDB<KeccakHasher, DBValue> + 'db> { ) -> Box<dyn HashDB<KeccakHasher, DBValue> + 'db> {
match *self { match *self {
Factory::Mangled => Box::new(AccountDB::from_hash(db, address_hash)), Factory::Mangled => Box::new(AccountDB::from_hash(db, address_hash)),
Factory::Plain => Box::new(Wrapping(db)), Factory::Plain => Box::new(Wrapping(db)),
@ -73,9 +73,9 @@ impl Factory {
/// Create a new mutable hashdb. /// Create a new mutable hashdb.
pub fn create<'db>( pub fn create<'db>(
&self, &self,
db: &'db mut HashDB<KeccakHasher, DBValue>, db: &'db mut dyn HashDB<KeccakHasher, DBValue>,
address_hash: H256, address_hash: H256,
) -> Box<HashDB<KeccakHasher, DBValue> + 'db> { ) -> Box<dyn HashDB<KeccakHasher, DBValue> + 'db> {
match *self { match *self {
Factory::Mangled => Box::new(AccountDBMut::from_hash(db, address_hash)), Factory::Mangled => Box::new(AccountDBMut::from_hash(db, address_hash)),
Factory::Plain => Box::new(WrappingMut(db)), Factory::Plain => Box::new(WrappingMut(db)),
@ -87,19 +87,19 @@ impl Factory {
/// DB backend wrapper for Account trie /// DB backend wrapper for Account trie
/// Transforms trie node keys for the database /// Transforms trie node keys for the database
pub struct AccountDB<'db> { pub struct AccountDB<'db> {
db: &'db HashDB<KeccakHasher, DBValue>, db: &'db dyn HashDB<KeccakHasher, DBValue>,
address_hash: H256, address_hash: H256,
} }
impl<'db> AccountDB<'db> { impl<'db> AccountDB<'db> {
/// Create a new AccountDB from an address. /// Create a new AccountDB from an address.
#[cfg(test)] #[cfg(test)]
pub fn new(db: &'db HashDB<KeccakHasher, DBValue>, address: &Address) -> Self { pub fn new(db: &'db dyn HashDB<KeccakHasher, DBValue>, address: &Address) -> Self {
Self::from_hash(db, keccak(address)) Self::from_hash(db, keccak(address))
} }
/// Create a new AcountDB from an address' hash. /// Create a new AcountDB from an address' hash.
pub fn from_hash(db: &'db HashDB<KeccakHasher, DBValue>, address_hash: H256) -> Self { pub fn from_hash(db: &'db dyn HashDB<KeccakHasher, DBValue>, address_hash: H256) -> Self {
AccountDB { AccountDB {
db: db, db: db,
address_hash: address_hash, address_hash: address_hash,
@ -108,10 +108,10 @@ impl<'db> AccountDB<'db> {
} }
impl<'db> AsHashDB<KeccakHasher, DBValue> for AccountDB<'db> { impl<'db> AsHashDB<KeccakHasher, DBValue> for AccountDB<'db> {
fn as_hash_db(&self) -> &HashDB<KeccakHasher, DBValue> { fn as_hash_db(&self) -> &dyn HashDB<KeccakHasher, DBValue> {
self self
} }
fn as_hash_db_mut(&mut self) -> &mut HashDB<KeccakHasher, DBValue> { fn as_hash_db_mut(&mut self) -> &mut dyn HashDB<KeccakHasher, DBValue> {
self self
} }
} }
@ -146,19 +146,19 @@ impl<'db> HashDB<KeccakHasher, DBValue> for AccountDB<'db> {
/// DB backend wrapper for Account trie /// DB backend wrapper for Account trie
pub struct AccountDBMut<'db> { pub struct AccountDBMut<'db> {
db: &'db mut HashDB<KeccakHasher, DBValue>, db: &'db mut dyn HashDB<KeccakHasher, DBValue>,
address_hash: H256, address_hash: H256,
} }
impl<'db> AccountDBMut<'db> { impl<'db> AccountDBMut<'db> {
/// Create a new AccountDB from an address. /// Create a new AccountDB from an address.
#[cfg(test)] #[cfg(test)]
pub fn new(db: &'db mut HashDB<KeccakHasher, DBValue>, address: &Address) -> Self { pub fn new(db: &'db mut dyn HashDB<KeccakHasher, DBValue>, address: &Address) -> Self {
Self::from_hash(db, keccak(address)) Self::from_hash(db, keccak(address))
} }
/// Create a new AcountDB from an address' hash. /// Create a new AcountDB from an address' hash.
pub fn from_hash(db: &'db mut HashDB<KeccakHasher, DBValue>, address_hash: H256) -> Self { pub fn from_hash(db: &'db mut dyn HashDB<KeccakHasher, DBValue>, address_hash: H256) -> Self {
AccountDBMut { AccountDBMut {
db: db, db: db,
address_hash: address_hash, address_hash: address_hash,
@ -217,21 +217,21 @@ impl<'db> HashDB<KeccakHasher, DBValue> for AccountDBMut<'db> {
} }
impl<'db> AsHashDB<KeccakHasher, DBValue> for AccountDBMut<'db> { impl<'db> AsHashDB<KeccakHasher, DBValue> for AccountDBMut<'db> {
fn as_hash_db(&self) -> &HashDB<KeccakHasher, DBValue> { fn as_hash_db(&self) -> &dyn HashDB<KeccakHasher, DBValue> {
self self
} }
fn as_hash_db_mut(&mut self) -> &mut HashDB<KeccakHasher, DBValue> { fn as_hash_db_mut(&mut self) -> &mut dyn HashDB<KeccakHasher, DBValue> {
self self
} }
} }
struct Wrapping<'db>(&'db HashDB<KeccakHasher, DBValue>); struct Wrapping<'db>(&'db dyn HashDB<KeccakHasher, DBValue>);
impl<'db> AsHashDB<KeccakHasher, DBValue> for Wrapping<'db> { impl<'db> AsHashDB<KeccakHasher, DBValue> for Wrapping<'db> {
fn as_hash_db(&self) -> &HashDB<KeccakHasher, DBValue> { fn as_hash_db(&self) -> &dyn HashDB<KeccakHasher, DBValue> {
self self
} }
fn as_hash_db_mut(&mut self) -> &mut HashDB<KeccakHasher, DBValue> { fn as_hash_db_mut(&mut self) -> &mut dyn HashDB<KeccakHasher, DBValue> {
self self
} }
} }
@ -264,12 +264,12 @@ impl<'db> HashDB<KeccakHasher, DBValue> for Wrapping<'db> {
} }
} }
struct WrappingMut<'db>(&'db mut HashDB<KeccakHasher, DBValue>); struct WrappingMut<'db>(&'db mut dyn HashDB<KeccakHasher, DBValue>);
impl<'db> AsHashDB<KeccakHasher, DBValue> for WrappingMut<'db> { impl<'db> AsHashDB<KeccakHasher, DBValue> for WrappingMut<'db> {
fn as_hash_db(&self) -> &HashDB<KeccakHasher, DBValue> { fn as_hash_db(&self) -> &dyn HashDB<KeccakHasher, DBValue> {
self self
} }
fn as_hash_db_mut(&mut self) -> &mut HashDB<KeccakHasher, DBValue> { fn as_hash_db_mut(&mut self) -> &mut dyn HashDB<KeccakHasher, DBValue> {
self self
} }
} }

View File

@ -61,7 +61,7 @@ use types::{
/// maintain the system `state()`. We also archive execution receipts in preparation for later block creation. /// maintain the system `state()`. We also archive execution receipts in preparation for later block creation.
pub struct OpenBlock<'x> { pub struct OpenBlock<'x> {
block: ExecutedBlock, 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, /// 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> { impl<'x> OpenBlock<'x> {
/// Create a new `OpenBlock` ready for transaction pushing. /// Create a new `OpenBlock` ready for transaction pushing.
pub fn new<'a, I: IntoIterator<Item = ExtendedHeader>>( pub fn new<'a, I: IntoIterator<Item = ExtendedHeader>>(
engine: &'x EthEngine, engine: &'x dyn EthEngine,
factories: Factories, factories: Factories,
tracing: bool, tracing: bool,
db: StateDB, db: StateDB,
@ -421,7 +421,7 @@ impl ClosedBlock {
} }
/// Given an engine reference, reopen the `ClosedBlock` into an `OpenBlock`. /// 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). // revert rewards (i.e. set state back at last transaction's state).
let mut block = self.block; let mut block = self.block;
block.state = self.unclosed_state; block.state = self.unclosed_state;
@ -451,7 +451,7 @@ impl LockedBlock {
/// Provide a valid seal in order to turn this into a `SealedBlock`. /// Provide a valid seal in order to turn this into a `SealedBlock`.
/// ///
/// NOTE: This does not check the validity of `seal` with the engine. /// NOTE: This does not check the validity of `seal` with the engine.
pub fn seal(self, engine: &EthEngine, seal: Vec<Bytes>) -> Result<SealedBlock, Error> { pub fn seal(self, engine: &dyn EthEngine, seal: Vec<Bytes>) -> Result<SealedBlock, Error> {
let expected_seal_fields = engine.seal_fields(&self.header); let expected_seal_fields = engine.seal_fields(&self.header);
let mut s = self; let mut s = self;
if seal.len() != expected_seal_fields { if seal.len() != expected_seal_fields {
@ -472,7 +472,7 @@ impl LockedBlock {
/// This does check the validity of `seal` with the engine. /// This does check the validity of `seal` with the engine.
/// Returns the `ClosedBlock` back again if the seal is no good. /// 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. /// 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<Bytes>) -> Result<SealedBlock, Error> { pub fn try_seal(self, engine: &dyn EthEngine, seal: Vec<Bytes>) -> Result<SealedBlock, Error> {
let mut s = self; let mut s = self;
s.block.header.set_seal(seal); s.block.header.set_seal(seal);
s.block.header.compute_hash(); s.block.header.compute_hash();
@ -511,14 +511,14 @@ pub(crate) fn enact(
header: Header, header: Header,
transactions: Vec<SignedTransaction>, transactions: Vec<SignedTransaction>,
uncles: Vec<Header>, uncles: Vec<Header>,
engine: &EthEngine, engine: &dyn EthEngine,
tracing: bool, tracing: bool,
db: StateDB, db: StateDB,
parent: &Header, parent: &Header,
last_hashes: Arc<LastHashes>, last_hashes: Arc<LastHashes>,
factories: Factories, factories: Factories,
is_epoch_begin: bool, is_epoch_begin: bool,
ancestry: &mut Iterator<Item = ExtendedHeader>, ancestry: &mut dyn Iterator<Item = ExtendedHeader>,
) -> Result<LockedBlock, Error> { ) -> Result<LockedBlock, Error> {
// For trace log // For trace log
let trace_state = if log_enabled!(target: "enact", ::log::Level::Trace) { 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 /// Enact the block given by `block_bytes` using `engine` on the database `db` with given `parent` block header
pub fn enact_verified( pub fn enact_verified(
block: PreverifiedBlock, block: PreverifiedBlock,
engine: &EthEngine, engine: &dyn EthEngine,
tracing: bool, tracing: bool,
db: StateDB, db: StateDB,
parent: &Header, parent: &Header,
last_hashes: Arc<LastHashes>, last_hashes: Arc<LastHashes>,
factories: Factories, factories: Factories,
is_epoch_begin: bool, is_epoch_begin: bool,
ancestry: &mut Iterator<Item = ExtendedHeader>, ancestry: &mut dyn Iterator<Item = ExtendedHeader>,
) -> Result<LockedBlock, Error> { ) -> Result<LockedBlock, Error> {
enact( enact(
block.header, 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 /// Enact the block given by `block_bytes` using `engine` on the database `db` with given `parent` block header
fn enact_bytes( fn enact_bytes(
block_bytes: Vec<u8>, block_bytes: Vec<u8>,
engine: &EthEngine, engine: &dyn EthEngine,
tracing: bool, tracing: bool,
db: StateDB, db: StateDB,
parent: &Header, 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 /// 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( fn enact_and_seal(
block_bytes: Vec<u8>, block_bytes: Vec<u8>,
engine: &EthEngine, engine: &dyn EthEngine,
tracing: bool, tracing: bool,
db: StateDB, db: StateDB,
parent: &Header, parent: &Header,

View File

@ -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 /// Ancient block verifier: import an ancient sequence of blocks in order from a starting
/// epoch. /// epoch.
pub struct AncientVerifier { pub struct AncientVerifier {
cur_verifier: RwLock<Option<Box<EpochVerifier<EthereumMachine>>>>, cur_verifier: RwLock<Option<Box<dyn EpochVerifier<EthereumMachine>>>>,
engine: Arc<EthEngine>, engine: Arc<dyn EthEngine>,
} }
impl AncientVerifier { impl AncientVerifier {
/// Create a new ancient block verifier with the given engine. /// Create a new ancient block verifier with the given engine.
pub fn new(engine: Arc<EthEngine>) -> Self { pub fn new(engine: Arc<dyn EthEngine>) -> Self {
AncientVerifier { AncientVerifier {
cur_verifier: RwLock::new(None), cur_verifier: RwLock::new(None),
engine, engine,
@ -93,7 +93,7 @@ impl AncientVerifier {
&self, &self,
header: &Header, header: &Header,
chain: &BlockChain, chain: &BlockChain,
) -> Result<Box<EpochVerifier<EthereumMachine>>, ::error::Error> { ) -> Result<Box<dyn EpochVerifier<EthereumMachine>>, ::error::Error> {
trace!(target: "client", "Initializing ancient block restoration."); trace!(target: "client", "Initializing ancient block restoration.");
let current_epoch_data = chain let current_epoch_data = chain
.epoch_transitions() .epoch_transitions()

View File

@ -184,7 +184,7 @@ struct Importer {
pub ancient_verifier: AncientVerifier, pub ancient_verifier: AncientVerifier,
/// Ethereum engine to be used during import /// Ethereum engine to be used during import
pub engine: Arc<EthEngine>, pub engine: Arc<dyn EthEngine>,
/// A lru cache of recently detected bad blocks /// A lru cache of recently detected bad blocks
pub bad_blocks: bad_blocks::BadBlocks, pub bad_blocks: bad_blocks::BadBlocks,
@ -206,7 +206,7 @@ pub struct Client {
chain: RwLock<Arc<BlockChain>>, chain: RwLock<Arc<BlockChain>>,
tracedb: RwLock<TraceDB<BlockChain>>, tracedb: RwLock<TraceDB<BlockChain>>,
engine: Arc<EthEngine>, engine: Arc<dyn EthEngine>,
/// Client configuration /// Client configuration
config: ClientConfig, config: ClientConfig,
@ -261,7 +261,7 @@ pub struct Client {
impl Importer { impl Importer {
pub fn new( pub fn new(
config: &ClientConfig, config: &ClientConfig,
engine: Arc<EthEngine>, engine: Arc<dyn EthEngine>,
message_channel: IoChannel<ClientIoMessage>, message_channel: IoChannel<ClientIoMessage>,
miner: Arc<Miner>, miner: Arc<Miner>,
) -> Result<Importer, EthcoreError> { ) -> Result<Importer, EthcoreError> {
@ -517,7 +517,7 @@ impl Importer {
&self, &self,
unverified: Unverified, unverified: Unverified,
receipts_bytes: &[u8], receipts_bytes: &[u8],
db: &KeyValueDB, db: &dyn KeyValueDB,
chain: &BlockChain, chain: &BlockChain,
) -> EthcoreResult<()> { ) -> EthcoreResult<()> {
let receipts = ::rlp::decode_list(receipts_bytes); let receipts = ::rlp::decode_list(receipts_bytes);
@ -833,7 +833,7 @@ impl Client {
pub fn new( pub fn new(
config: ClientConfig, config: ClientConfig,
spec: &Spec, spec: &Spec,
db: Arc<BlockChainDB>, db: Arc<dyn BlockChainDB>,
miner: Arc<Miner>, miner: Arc<Miner>,
message_channel: IoChannel<ClientIoMessage>, message_channel: IoChannel<ClientIoMessage>,
) -> Result<Arc<Client>, ::error::Error> { ) -> Result<Arc<Client>, ::error::Error> {
@ -999,7 +999,7 @@ impl Client {
} }
/// Adds an actor to be notified on certain events /// Adds an actor to be notified on certain events
pub fn add_notify(&self, target: Arc<ChainNotify>) { pub fn add_notify(&self, target: Arc<dyn ChainNotify>) {
self.notify.write().push(Arc::downgrade(&target)); self.notify.write().push(Arc::downgrade(&target));
} }
@ -1015,13 +1015,13 @@ impl Client {
} }
/// Returns engine reference. /// Returns engine reference.
pub fn engine(&self) -> &EthEngine { pub fn engine(&self) -> &dyn EthEngine {
&*self.engine &*self.engine
} }
fn notify<F>(&self, f: F) fn notify<F>(&self, f: F)
where where
F: Fn(&ChainNotify), F: Fn(&dyn ChainNotify),
{ {
for np in &*self.notify.read() { for np in &*self.notify.read() {
if let Some(n) = np.upgrade() { if let Some(n) = np.upgrade() {
@ -1936,7 +1936,7 @@ impl Call for Client {
} }
impl EngineInfo for Client { impl EngineInfo for Client {
fn engine(&self) -> &EthEngine { fn engine(&self) -> &dyn EthEngine {
Client::engine(self) Client::engine(self)
} }
} }
@ -1967,7 +1967,7 @@ impl BlockChainClient for Client {
&self, &self,
block: BlockId, block: BlockId,
analytics: CallAnalytics, analytics: CallAnalytics,
) -> Result<Box<Iterator<Item = (H256, Executed)>>, CallError> { ) -> Result<Box<dyn Iterator<Item = (H256, Executed)>>, CallError> {
let mut env_info = self.env_info(block).ok_or(CallError::StatePruned)?; let mut env_info = self.env_info(block).ok_or(CallError::StatePruned)?;
let body = self.block_body(block).ok_or(CallError::StatePruned)?; let body = self.block_body(block).ok_or(CallError::StatePruned)?;
let mut state = self let mut state = self
@ -2895,7 +2895,7 @@ impl super::traits::EngineClient for Client {
self.chain.read().epoch_transition_for(parent_hash) 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) Some(self)
} }

View File

@ -47,7 +47,7 @@ impl ClientIoMessage {
} }
/// A function to invoke in the client thread. /// A function to invoke in the client thread.
pub struct Callback(pub Box<Fn(&Client) + Send + Sync>); pub struct Callback(pub Box<dyn Fn(&Client) + Send + Sync>);
impl fmt::Debug for Callback { impl fmt::Debug for Callback {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {

View File

@ -715,7 +715,7 @@ impl StateClient for TestBlockChainClient {
} }
impl EngineInfo for TestBlockChainClient { impl EngineInfo for TestBlockChainClient {
fn engine(&self) -> &EthEngine { fn engine(&self) -> &dyn EthEngine {
unimplemented!() unimplemented!()
} }
} }
@ -743,7 +743,7 @@ impl BlockChainClient for TestBlockChainClient {
&self, &self,
_block: BlockId, _block: BlockId,
_analytics: CallAnalytics, _analytics: CallAnalytics,
) -> Result<Box<Iterator<Item = (H256, Executed)>>, CallError> { ) -> Result<Box<dyn Iterator<Item = (H256, Executed)>>, CallError> {
Ok(Box::new( Ok(Box::new(
self.traces self.traces
.read() .read()
@ -1110,7 +1110,7 @@ impl super::traits::EngineClient for TestBlockChainClient {
None None
} }
fn as_full_client(&self) -> Option<&BlockChainClient> { fn as_full_client(&self) -> Option<&dyn BlockChainClient> {
Some(self) Some(self)
} }

View File

@ -23,11 +23,11 @@ use types::BlockNumber;
impl TraceDatabaseExtras for BlockChain { impl TraceDatabaseExtras for BlockChain {
fn block_hash(&self, block_number: BlockNumber) -> Option<H256> { fn block_hash(&self, block_number: BlockNumber) -> Option<H256> {
(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<H256> { fn transaction_hash(&self, block_number: BlockNumber, tx_position: usize) -> Option<H256> {
(self as &BlockProvider) (self as &dyn BlockProvider)
.block_hash(block_number) .block_hash(block_number)
.and_then(|block_hash| { .and_then(|block_hash| {
let tx_address = TransactionAddress { let tx_address = TransactionAddress {

View File

@ -56,7 +56,7 @@ use verification::queue::{kind::blocks::Unverified, QueueInfo as BlockQueueInfo}
/// State information to be used during client query /// State information to be used during client query
pub enum StateOrBlock { pub enum StateOrBlock {
/// State to be used, may be pending /// State to be used, may be pending
State(Box<StateInfo>), State(Box<dyn StateInfo>),
/// Id of an existing block from a chain to get state from /// Id of an existing block from a chain to get state from
Block(BlockId), Block(BlockId),
@ -68,8 +68,8 @@ impl<S: StateInfo + 'static> From<S> for StateOrBlock {
} }
} }
impl From<Box<StateInfo>> for StateOrBlock { impl From<Box<dyn StateInfo>> for StateOrBlock {
fn from(info: Box<StateInfo>) -> StateOrBlock { fn from(info: Box<dyn StateInfo>) -> StateOrBlock {
StateOrBlock::State(info) StateOrBlock::State(info)
} }
} }
@ -203,7 +203,7 @@ pub trait Call {
/// Provides `engine` method /// Provides `engine` method
pub trait EngineInfo { pub trait EngineInfo {
/// Get underlying engine object /// Get underlying engine object
fn engine(&self) -> &EthEngine; fn engine(&self) -> &dyn EthEngine;
} }
/// IO operations that should off-load heavy work to another thread. /// IO operations that should off-load heavy work to another thread.
@ -353,7 +353,7 @@ pub trait BlockChainClient:
&self, &self,
block: BlockId, block: BlockId,
analytics: CallAnalytics, analytics: CallAnalytics,
) -> Result<Box<Iterator<Item = (H256, Executed)>>, CallError>; ) -> Result<Box<dyn Iterator<Item = (H256, Executed)>>, CallError>;
/// Returns traces matching given filter. /// Returns traces matching given filter.
fn filter_traces(&self, filter: TraceFilter) -> Option<Vec<LocalizedTrace>>; fn filter_traces(&self, filter: TraceFilter) -> Option<Vec<LocalizedTrace>>;
@ -501,7 +501,7 @@ pub trait EngineClient: Sync + Send + ChainInfo {
fn epoch_transition_for(&self, parent_hash: H256) -> Option<::engines::EpochTransition>; fn epoch_transition_for(&self, parent_hash: H256) -> Option<::engines::EpochTransition>;
/// Attempt to cast the engine client to a full client. /// 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. /// Get a block number by ID.
fn block_number(&self, id: BlockId) -> Option<BlockNumber>; fn block_number(&self, id: BlockId) -> Option<BlockNumber>;

View File

@ -72,7 +72,7 @@ pub struct AuthorityRoundParams {
/// Starting step, /// Starting step,
pub start_step: Option<u64>, pub start_step: Option<u64>,
/// Valid validators. /// Valid validators.
pub validators: Box<ValidatorSet>, pub validators: Box<dyn ValidatorSet>,
/// Chain score validation transition block. /// Chain score validation transition block.
pub validate_score_transition: u64, pub validate_score_transition: u64,
/// Monotonic step validation transition block. /// Monotonic step validation transition block.
@ -240,9 +240,9 @@ impl EpochManager {
// zoom to epoch for given header. returns true if succeeded, false otherwise. // zoom to epoch for given header. returns true if succeeded, false otherwise.
fn zoom_to( fn zoom_to(
&mut self, &mut self,
client: &EngineClient, client: &dyn EngineClient,
machine: &EthereumMachine, machine: &EthereumMachine,
validators: &ValidatorSet, validators: &dyn ValidatorSet,
header: &Header, header: &Header,
) -> bool { ) -> bool {
let last_was_parent = self.finality_checker.subchain_head() == Some(*header.parent_hash()); 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<bool, Error> { fn verify(&self, validators: &dyn ValidatorSet) -> Result<bool, Error> {
let message = keccak(empty_step_rlp(self.step, &self.parent_hash)); let message = keccak(empty_step_rlp(self.step, &self.parent_hash));
let correct_proposer = step_proposer(validators, &self.parent_hash, self.step); let correct_proposer = step_proposer(validators, &self.parent_hash, self.step);
@ -449,9 +449,9 @@ struct PermissionedStep {
pub struct AuthorityRound { pub struct AuthorityRound {
transition_service: IoService<()>, transition_service: IoService<()>,
step: Arc<PermissionedStep>, step: Arc<PermissionedStep>,
client: Arc<RwLock<Option<Weak<EngineClient>>>>, client: Arc<RwLock<Option<Weak<dyn EngineClient>>>>,
signer: RwLock<Option<Box<EngineSigner>>>, signer: RwLock<Option<Box<dyn EngineSigner>>>,
validators: Box<ValidatorSet>, validators: Box<dyn ValidatorSet>,
validate_score_transition: u64, validate_score_transition: u64,
validate_step_transition: u64, validate_step_transition: u64,
empty_steps: Mutex<BTreeSet<EmptyStep>>, empty_steps: Mutex<BTreeSet<EmptyStep>>,
@ -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); let proposer = validators.get(bh, step as usize);
trace!(target: "engine", "Fetched proposer for step {}: {}", step, proposer); trace!(target: "engine", "Fetched proposer for step {}: {}", step, proposer);
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 step_proposer(validators, bh, step) == *address
} }
@ -671,7 +676,7 @@ fn verify_timestamp(step: &Step, header_step: u64) -> Result<(), BlockError> {
fn verify_external( fn verify_external(
header: &Header, header: &Header,
validators: &ValidatorSet, validators: &dyn ValidatorSet,
empty_steps_transition: u64, empty_steps_transition: u64,
) -> Result<(), Error> { ) -> Result<(), Error> {
let header_step = header_step(header, empty_steps_transition)?; let header_step = header_step(header, empty_steps_transition)?;
@ -805,7 +810,7 @@ impl AuthorityRound {
fn epoch_set<'a>( fn epoch_set<'a>(
&'a self, &'a self,
header: &Header, header: &Header,
) -> Result<(CowLike<ValidatorSet, SimpleList>, BlockNumber), Error> { ) -> Result<(CowLike<dyn ValidatorSet, SimpleList>, BlockNumber), Error> {
Ok(if self.immediate_transitions { Ok(if self.immediate_transitions {
(CowLike::Borrowed(&*self.validators), header.number()) (CowLike::Borrowed(&*self.validators), header.number())
} else { } else {
@ -903,7 +908,7 @@ impl AuthorityRound {
header: &Header, header: &Header,
current_step: u64, current_step: u64,
parent_step: u64, parent_step: u64,
validators: &ValidatorSet, validators: &dyn ValidatorSet,
set_number: u64, set_number: u64,
) { ) {
// we're building on top of the genesis block so don't report any skipped steps // 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( fn build_finality(
&self, &self,
chain_head: &Header, chain_head: &Header,
ancestry: &mut Iterator<Item = Header>, ancestry: &mut dyn Iterator<Item = Header>,
) -> Vec<H256> { ) -> Vec<H256> {
if self.immediate_transitions { if self.immediate_transitions {
return Vec::new(); return Vec::new();
@ -1019,7 +1024,7 @@ fn unix_now() -> Duration {
struct TransitionHandler { struct TransitionHandler {
step: Arc<PermissionedStep>, step: Arc<PermissionedStep>,
client: Arc<RwLock<Option<Weak<EngineClient>>>>, client: Arc<RwLock<Option<Weak<dyn EngineClient>>>>,
} }
const ENGINE_TIMEOUT_TOKEN: TimerToken = 23; const ENGINE_TIMEOUT_TOKEN: TimerToken = 23;
@ -1306,7 +1311,7 @@ impl Engine<EthereumMachine> for AuthorityRound {
&self, &self,
block: &mut ExecutedBlock, block: &mut ExecutedBlock,
epoch_begin: bool, epoch_begin: bool,
_ancestry: &mut Iterator<Item = ExtendedHeader>, _ancestry: &mut dyn Iterator<Item = ExtendedHeader>,
) -> Result<(), Error> { ) -> Result<(), Error> {
// with immediate transitions, we don't use the epoch mechanism anyway. // with immediate transitions, we don't use the epoch mechanism anyway.
// the genesis is always considered an epoch, but we ignore it intentionally. // the genesis is always considered an epoch, but we ignore it intentionally.
@ -1728,12 +1733,12 @@ impl Engine<EthereumMachine> for AuthorityRound {
} }
} }
fn register_client(&self, client: Weak<EngineClient>) { fn register_client(&self, client: Weak<dyn EngineClient>) {
*self.client.write() = Some(client.clone()); *self.client.write() = Some(client.clone());
self.validators.register_client(client); self.validators.register_client(client);
} }
fn set_signer(&self, signer: Box<EngineSigner>) { fn set_signer(&self, signer: Box<dyn EngineSigner>) {
*self.signer.write() = Some(signer); *self.signer.write() = Some(signer);
} }
@ -1746,7 +1751,7 @@ impl Engine<EthereumMachine> for AuthorityRound {
.sign(hash)?) .sign(hash)?)
} }
fn snapshot_components(&self) -> Option<Box<::snapshot::SnapshotComponents>> { fn snapshot_components(&self) -> Option<Box<dyn crate::snapshot::SnapshotComponents>> {
if self.immediate_transitions { if self.immediate_transitions {
None None
} else { } else {
@ -1761,7 +1766,7 @@ impl Engine<EthereumMachine> for AuthorityRound {
fn ancestry_actions( fn ancestry_actions(
&self, &self,
header: &Header, header: &Header,
ancestry: &mut Iterator<Item = ExtendedHeader>, ancestry: &mut dyn Iterator<Item = ExtendedHeader>,
) -> Vec<AncestryAction> { ) -> Vec<AncestryAction> {
let finalized = self.build_finality( let finalized = self.build_finality(
header, header,
@ -2171,7 +2176,7 @@ mod tests {
(spec, tap, accounts) (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 empty_step_rlp = super::empty_step_rlp(step, parent_hash);
let signature = engine.sign(keccak(&empty_step_rlp)).unwrap().into(); let signature = engine.sign(keccak(&empty_step_rlp)).unwrap().into();
let parent_hash = parent_hash.clone(); 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 empty_step_rlp = super::empty_step_rlp(step, parent_hash);
let signature = engine.sign(keccak(&empty_step_rlp)).unwrap().into(); let signature = engine.sign(keccak(&empty_step_rlp)).unwrap().into();
SealedEmptyStep { signature, step } SealedEmptyStep { signature, step }

View File

@ -54,7 +54,7 @@ impl super::EpochVerifier<EthereumMachine> for EpochVerifier {
} }
} }
fn verify_external(header: &Header, validators: &ValidatorSet) -> Result<(), Error> { fn verify_external(header: &Header, validators: &dyn ValidatorSet) -> Result<(), Error> {
use rlp::Rlp; use rlp::Rlp;
// Check if the signature belongs to a validator, can depend on parent state. // 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. /// Engine using `BasicAuthority`, trivial proof-of-authority consensus.
pub struct BasicAuthority { pub struct BasicAuthority {
machine: EthereumMachine, machine: EthereumMachine,
signer: RwLock<Option<Box<EngineSigner>>>, signer: RwLock<Option<Box<dyn EngineSigner>>>,
validators: Box<ValidatorSet>, validators: Box<dyn ValidatorSet>,
} }
impl BasicAuthority { impl BasicAuthority {
@ -201,11 +201,11 @@ impl Engine<EthereumMachine> for BasicAuthority {
} }
} }
fn register_client(&self, client: Weak<EngineClient>) { fn register_client(&self, client: Weak<dyn EngineClient>) {
self.validators.register_client(client); self.validators.register_client(client);
} }
fn set_signer(&self, signer: Box<EngineSigner>) { fn set_signer(&self, signer: Box<dyn EngineSigner>) {
*self.signer.write() = Some(signer); *self.signer.write() = Some(signer);
} }
@ -218,7 +218,7 @@ impl Engine<EthereumMachine> for BasicAuthority {
.sign(hash)?) .sign(hash)?)
} }
fn snapshot_components(&self) -> Option<Box<::snapshot::SnapshotComponents>> { fn snapshot_components(&self) -> Option<Box<dyn crate::snapshot::SnapshotComponents>> {
None None
} }

View File

@ -163,10 +163,10 @@ pub struct Clique {
epoch_length: u64, epoch_length: u64,
period: u64, period: u64,
machine: EthereumMachine, machine: EthereumMachine,
client: RwLock<Option<Weak<EngineClient>>>, client: RwLock<Option<Weak<dyn EngineClient>>>,
block_state_by_hash: RwLock<LruCache<H256, CliqueBlockState>>, block_state_by_hash: RwLock<LruCache<H256, CliqueBlockState>>,
proposals: RwLock<HashMap<Address, VoteType>>, proposals: RwLock<HashMap<Address, VoteType>>,
signer: RwLock<Option<Box<EngineSigner>>>, signer: RwLock<Option<Box<dyn EngineSigner>>>,
} }
#[cfg(test)] #[cfg(test)]
@ -175,10 +175,10 @@ pub struct Clique {
pub epoch_length: u64, pub epoch_length: u64,
pub period: u64, pub period: u64,
pub machine: EthereumMachine, pub machine: EthereumMachine,
pub client: RwLock<Option<Weak<EngineClient>>>, pub client: RwLock<Option<Weak<dyn EngineClient>>>,
pub block_state_by_hash: RwLock<LruCache<H256, CliqueBlockState>>, pub block_state_by_hash: RwLock<LruCache<H256, CliqueBlockState>>,
pub proposals: RwLock<HashMap<Address, VoteType>>, pub proposals: RwLock<HashMap<Address, VoteType>>,
pub signer: RwLock<Option<Box<EngineSigner>>>, pub signer: RwLock<Option<Box<dyn EngineSigner>>>,
} }
impl Clique { impl Clique {
@ -383,7 +383,7 @@ impl Engine<EthereumMachine> for Clique {
&self, &self,
_block: &mut ExecutedBlock, _block: &mut ExecutedBlock,
_epoch_begin: bool, _epoch_begin: bool,
_ancestry: &mut Iterator<Item = ExtendedHeader>, _ancestry: &mut dyn Iterator<Item = ExtendedHeader>,
) -> Result<(), Error> { ) -> Result<(), Error> {
Ok(()) Ok(())
} }
@ -767,12 +767,12 @@ impl Engine<EthereumMachine> for Clique {
} }
} }
fn set_signer(&self, signer: Box<EngineSigner>) { fn set_signer(&self, signer: Box<dyn EngineSigner>) {
trace!(target: "engine", "set_signer: {}", signer.address()); trace!(target: "engine", "set_signer: {}", signer.address());
*self.signer.write() = Some(signer); *self.signer.write() = Some(signer);
} }
fn register_client(&self, client: Weak<EngineClient>) { fn register_client(&self, client: Weak<dyn EngineClient>) {
*self.client.write() = Some(client.clone()); *self.client.write() = Some(client.clone());
} }

View File

@ -181,11 +181,11 @@ pub enum Seal {
} }
/// A system-calling closure. Enacts calls on a block's state from the system address. /// A system-calling closure. Enacts calls on a block's state from the system address.
pub type SystemCall<'a> = FnMut(Address, Vec<u8>) -> Result<Vec<u8>, String> + 'a; pub type SystemCall<'a> = dyn FnMut(Address, Vec<u8>) -> Result<Vec<u8>, 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. /// 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> = pub type SystemOrCodeCall<'a> =
FnMut(SystemOrCodeCallKind, Vec<u8>) -> Result<Vec<u8>, String> + 'a; dyn FnMut(SystemOrCodeCallKind, Vec<u8>) -> Result<Vec<u8>, String> + 'a;
/// Kind of SystemOrCodeCall, this is either an on-chain address, or code. /// Kind of SystemOrCodeCall, this is either an on-chain address, or code.
#[derive(PartialEq, Debug, Clone)] #[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. /// Type alias for a function we can get headers by hash through.
pub type Headers<'a, H> = Fn(H256) -> Option<H> + 'a; pub type Headers<'a, H> = dyn Fn(H256) -> Option<H> + 'a;
/// Type alias for a function we can query pending transitions by block hash through. /// Type alias for a function we can query pending transitions by block hash through.
pub type PendingTransitionStore<'a> = Fn(H256) -> Option<epoch::PendingTransition> + 'a; pub type PendingTransitionStore<'a> = dyn Fn(H256) -> Option<epoch::PendingTransition> + 'a;
/// Proof dependent on state. /// Proof dependent on state.
pub trait StateDependentProof<M: Machine>: Send + Sync { pub trait StateDependentProof<M: Machine>: Send + Sync {
@ -243,16 +243,16 @@ pub enum Proof<M: Machine> {
/// Known proof (extracted from signal) /// Known proof (extracted from signal)
Known(Vec<u8>), Known(Vec<u8>),
/// State dependent proof. /// State dependent proof.
WithState(Arc<StateDependentProof<M>>), WithState(Arc<dyn StateDependentProof<M>>),
} }
/// Generated epoch verifier. /// Generated epoch verifier.
pub enum ConstructedVerifier<'a, M: Machine> { pub enum ConstructedVerifier<'a, M: Machine> {
/// Fully trusted verifier. /// Fully trusted verifier.
Trusted(Box<EpochVerifier<M>>), Trusted(Box<dyn EpochVerifier<M>>),
/// Verifier unconfirmed. Check whether given finality proof finalizes given hash /// Verifier unconfirmed. Check whether given finality proof finalizes given hash
/// under previous epoch. /// under previous epoch.
Unconfirmed(Box<EpochVerifier<M>>, &'a [u8], H256), Unconfirmed(Box<dyn EpochVerifier<M>>, &'a [u8], H256),
/// Error constructing verifier. /// Error constructing verifier.
Err(Error), Err(Error),
} }
@ -260,7 +260,7 @@ pub enum ConstructedVerifier<'a, M: Machine> {
impl<'a, M: Machine> ConstructedVerifier<'a, M> { impl<'a, M: Machine> ConstructedVerifier<'a, M> {
/// Convert to a result, indicating that any necessary confirmation has been done /// Convert to a result, indicating that any necessary confirmation has been done
/// already. /// already.
pub fn known_confirmed(self) -> Result<Box<EpochVerifier<M>>, Error> { pub fn known_confirmed(self) -> Result<Box<dyn EpochVerifier<M>>, Error> {
match self { match self {
ConstructedVerifier::Trusted(v) | ConstructedVerifier::Unconfirmed(v, _, _) => Ok(v), ConstructedVerifier::Trusted(v) | ConstructedVerifier::Unconfirmed(v, _, _) => Ok(v),
ConstructedVerifier::Err(e) => Err(e), ConstructedVerifier::Err(e) => Err(e),
@ -314,7 +314,7 @@ pub trait Engine<M: Machine>: Sync + Send {
&self, &self,
_block: &mut ExecutedBlock, _block: &mut ExecutedBlock,
_epoch_begin: bool, _epoch_begin: bool,
_ancestry: &mut Iterator<Item = ExtendedHeader>, _ancestry: &mut dyn Iterator<Item = ExtendedHeader>,
) -> Result<(), M::Error> { ) -> Result<(), M::Error> {
Ok(()) Ok(())
} }
@ -467,7 +467,7 @@ pub trait Engine<M: Machine>: Sync + Send {
} }
/// Register a component which signs consensus messages. /// Register a component which signs consensus messages.
fn set_signer(&self, _signer: Box<EngineSigner>) {} fn set_signer(&self, _signer: Box<dyn EngineSigner>) {}
/// Sign using the EngineSigner, to be used for consensus tx signing. /// Sign using the EngineSigner, to be used for consensus tx signing.
fn sign(&self, _hash: H256) -> Result<Signature, M::Error> { fn sign(&self, _hash: H256) -> Result<Signature, M::Error> {
@ -482,7 +482,7 @@ pub trait Engine<M: Machine>: Sync + Send {
/// Create a factory for building snapshot chunks and restoring from them. /// Create a factory for building snapshot chunks and restoring from them.
/// Returning `None` indicates that this engine doesn't support snapshot creation. /// Returning `None` indicates that this engine doesn't support snapshot creation.
fn snapshot_components(&self) -> Option<Box<SnapshotComponents>> { fn snapshot_components(&self) -> Option<Box<dyn SnapshotComponents>> {
None None
} }
@ -511,7 +511,7 @@ pub trait Engine<M: Machine>: Sync + Send {
fn ancestry_actions( fn ancestry_actions(
&self, &self,
_header: &Header, _header: &Header,
_ancestry: &mut Iterator<Item = ExtendedHeader>, _ancestry: &mut dyn Iterator<Item = ExtendedHeader>,
) -> Vec<AncestryAction> { ) -> Vec<AncestryAction> {
Vec::new() Vec::new()
} }

View File

@ -117,7 +117,7 @@ impl<M: Machine> Engine<M> for NullEngine<M> {
Ok(()) Ok(())
} }
fn snapshot_components(&self) -> Option<Box<::snapshot::SnapshotComponents>> { fn snapshot_components(&self) -> Option<Box<dyn crate::snapshot::SnapshotComponents>> {
Some(Box::new(::snapshot::PowSnapshot::new(10000, 10000))) Some(Box::new(::snapshot::PowSnapshot::new(10000, 10000)))
} }

View File

@ -29,7 +29,7 @@ pub trait EngineSigner: Send + Sync {
} }
/// Creates a new `EngineSigner` from given key pair. /// Creates a new `EngineSigner` from given key pair.
pub fn from_keypair(keypair: ethkey::KeyPair) -> Box<EngineSigner> { pub fn from_keypair(keypair: ethkey::KeyPair) -> Box<dyn EngineSigner> {
Box::new(Signer(keypair)) Box::new(Signer(keypair))
} }

View File

@ -34,7 +34,7 @@ use_contract!(validator_report, "res/contracts/validator_report.json");
pub struct ValidatorContract { pub struct ValidatorContract {
contract_address: Address, contract_address: Address,
validators: ValidatorSafeContract, validators: ValidatorSafeContract,
client: RwLock<Option<Weak<EngineClient>>>, // TODO [keorn]: remove client: RwLock<Option<Weak<dyn EngineClient>>>, // TODO [keorn]: remove
} }
impl ValidatorContract { impl ValidatorContract {
@ -143,7 +143,7 @@ impl ValidatorSet for ValidatorContract {
} }
} }
fn register_client(&self, client: Weak<EngineClient>) { fn register_client(&self, client: Weak<dyn EngineClient>) {
self.validators.register_client(client.clone()); self.validators.register_client(client.clone());
*self.client.write() = Some(client); *self.client.write() = Some(client);
} }

View File

@ -40,7 +40,7 @@ use self::{contract::ValidatorContract, multi::Multi, safe_contract::ValidatorSa
use super::SystemCall; use super::SystemCall;
/// Creates a validator set from spec. /// Creates a validator set from spec.
pub fn new_validator_set(spec: ValidatorSpec) -> Box<ValidatorSet> { pub fn new_validator_set(spec: ValidatorSpec) -> Box<dyn ValidatorSet> {
match spec { match spec {
ValidatorSpec::List(list) => { ValidatorSpec::List(list) => {
Box::new(SimpleList::new(list.into_iter().map(Into::into).collect())) 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. /// Notifies about benign misbehaviour.
fn report_benign(&self, _validator: &Address, _set_block: BlockNumber, _block: BlockNumber) {} fn report_benign(&self, _validator: &Address, _set_block: BlockNumber, _block: BlockNumber) {}
/// Allows blockchain state access. /// Allows blockchain state access.
fn register_client(&self, _client: Weak<EngineClient>) {} fn register_client(&self, _client: Weak<dyn EngineClient>) {}
} }

View File

@ -27,15 +27,16 @@ use super::{SystemCall, ValidatorSet};
use client::EngineClient; use client::EngineClient;
use machine::{AuxiliaryData, Call, EthereumMachine}; use machine::{AuxiliaryData, Call, EthereumMachine};
type BlockNumberLookup = Box<Fn(BlockId) -> Result<BlockNumber, String> + Send + Sync + 'static>; type BlockNumberLookup =
Box<dyn Fn(BlockId) -> Result<BlockNumber, String> + Send + Sync + 'static>;
pub struct Multi { pub struct Multi {
sets: BTreeMap<BlockNumber, Box<ValidatorSet>>, sets: BTreeMap<BlockNumber, Box<dyn ValidatorSet>>,
block_number: RwLock<BlockNumberLookup>, block_number: RwLock<BlockNumberLookup>,
} }
impl Multi { impl Multi {
pub fn new(set_map: BTreeMap<BlockNumber, Box<ValidatorSet>>) -> Self { pub fn new(set_map: BTreeMap<BlockNumber, Box<dyn ValidatorSet>>) -> Self {
assert!( assert!(
set_map.get(&0u64).is_some(), set_map.get(&0u64).is_some(),
"ValidatorSet has to be specified from block 0." "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) match self.block_number.read()(id)
.map(|parent_block| self.correct_set_by_number(parent_block)) .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 // get correct set by block number, along with block number at which
// this set was activated. // 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() let (block, set) = self.sets.iter()
.rev() .rev()
.find(|&(block, _)| *block <= parent_block + 1) .find(|&(block, _)| *block <= parent_block + 1)
@ -165,7 +166,7 @@ impl ValidatorSet for Multi {
.report_benign(validator, set_block, block); .report_benign(validator, set_block, block);
} }
fn register_client(&self, client: Weak<EngineClient>) { fn register_client(&self, client: Weak<dyn EngineClient>) {
for set in self.sets.values() { for set in self.sets.values() {
set.register_client(client.clone()); set.register_client(client.clone());
} }
@ -263,7 +264,7 @@ mod tests {
fn transition_to_fixed_list_instant() { fn transition_to_fixed_list_instant() {
use super::super::SimpleList; use super::super::SimpleList;
let mut map: BTreeMap<_, Box<ValidatorSet>> = BTreeMap::new(); let mut map: BTreeMap<_, Box<dyn ValidatorSet>> = BTreeMap::new();
let list1: Vec<_> = (0..10).map(|_| Address::random()).collect(); let list1: Vec<_> = (0..10).map(|_| Address::random()).collect();
let list2 = { let list2 = {
let mut list = list1.clone(); let mut list = list1.clone();

View File

@ -70,7 +70,7 @@ impl ::engines::StateDependentProof<EthereumMachine> for StateProof {
pub struct ValidatorSafeContract { pub struct ValidatorSafeContract {
contract_address: Address, contract_address: Address,
validators: RwLock<MemoryLruCache<H256, SimpleList>>, validators: RwLock<MemoryLruCache<H256, SimpleList>>,
client: RwLock<Option<Weak<EngineClient>>>, // TODO [keorn]: remove client: RwLock<Option<Weak<dyn EngineClient>>>, // TODO [keorn]: remove
} }
// first proof is just a state proof call of `getValidators` at header's state. // 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<EngineClient>) { fn register_client(&self, client: Weak<dyn EngineClient>) {
trace!(target: "engine", "Setting up contract caller."); trace!(target: "engine", "Setting up contract caller.");
*self.client.write() = Some(client); *self.client.write() = Some(client);
} }

View File

@ -114,8 +114,8 @@ impl ValidatorSet for SimpleList {
} }
} }
impl AsRef<ValidatorSet> for SimpleList { impl AsRef<dyn ValidatorSet> for SimpleList {
fn as_ref(&self) -> &ValidatorSet { fn as_ref(&self) -> &dyn ValidatorSet {
self self
} }
} }

View File

@ -444,7 +444,7 @@ impl Engine<EthereumMachine> for Arc<Ethash> {
engines::ConstructedVerifier::Trusted(Box::new(self.clone())) engines::ConstructedVerifier::Trusted(Box::new(self.clone()))
} }
fn snapshot_components(&self) -> Option<Box<::snapshot::SnapshotComponents>> { fn snapshot_components(&self) -> Option<Box<dyn crate::snapshot::SnapshotComponents>> {
Some(Box::new(::snapshot::PowSnapshot::new( Some(Box::new(::snapshot::PowSnapshot::new(
SNAPSHOT_BLOCKS, SNAPSHOT_BLOCKS,
MAX_SNAPSHOT_BLOCKS, MAX_SNAPSHOT_BLOCKS,

View File

@ -223,8 +223,8 @@ enum CallCreateExecutiveKind {
CallBuiltin(ActionParams), CallBuiltin(ActionParams),
ExecCall(ActionParams, Substate), ExecCall(ActionParams, Substate),
ExecCreate(ActionParams, Substate), ExecCreate(ActionParams, Substate),
ResumeCall(OriginInfo, Box<ResumeCall>, Substate), ResumeCall(OriginInfo, Box<dyn ResumeCall>, Substate),
ResumeCreate(OriginInfo, Box<ResumeCreate>, Substate), ResumeCreate(OriginInfo, Box<dyn ResumeCreate>, Substate),
} }
/// Executive for a raw call/create action. /// Executive for a raw call/create action.

View File

@ -31,7 +31,7 @@ pub struct VmFactory {
} }
impl VmFactory { impl VmFactory {
pub fn create(&self, params: ActionParams, schedule: &Schedule, depth: usize) -> Box<Exec> { pub fn create(&self, params: ActionParams, schedule: &Schedule, depth: usize) -> Box<dyn Exec> {
if schedule.wasm.is_some() if schedule.wasm.is_some()
&& params.code.as_ref().map_or(false, |code| { && params.code.as_ref().map_or(false, |code| {
code.len() > 4 && &code[0..4] == WASM_MAGIC_NUMBER code.len() > 4 && &code[0..4] == WASM_MAGIC_NUMBER

View File

@ -83,7 +83,7 @@ impl From<::ethjson::spec::EthashParams> for EthashExtensions {
} }
/// Special rules to be applied to the schedule. /// 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. /// An ethereum-like state machine.
pub struct EthereumMachine { pub struct EthereumMachine {
@ -479,7 +479,7 @@ pub struct AuxiliaryData<'a> {
/// Type alias for a function we can make calls through synchronously. /// Type alias for a function we can make calls through synchronously.
/// Returns the call result and state proof for each call. /// Returns the call result and state proof for each call.
pub type Call<'a> = Fn(Address, Vec<u8>) -> Result<(Vec<u8>, Vec<Vec<u8>>), String> + 'a; pub type Call<'a> = dyn Fn(Address, Vec<u8>) -> Result<(Vec<u8>, Vec<Vec<u8>>), String> + 'a;
/// Request for auxiliary data of a block. /// Request for auxiliary data of a block.
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq)]
@ -493,7 +493,7 @@ pub enum AuxiliaryRequest {
} }
impl super::Machine for EthereumMachine { impl super::Machine for EthereumMachine {
type EngineClient = ::client::EngineClient; type EngineClient = dyn crate::client::EngineClient;
type Error = Error; type Error = Error;

View File

@ -206,7 +206,7 @@ pub enum Author {
/// Sealing block is external and we only need a reward beneficiary (i.e. PoW) /// Sealing block is external and we only need a reward beneficiary (i.e. PoW)
External(Address), External(Address),
/// Sealing is done internally, we need a way to create signatures to seal block (i.e. PoA) /// Sealing is done internally, we need a way to create signatures to seal block (i.e. PoA)
Sealer(Box<EngineSigner>), Sealer(Box<dyn EngineSigner>),
} }
impl Author { impl Author {
@ -242,14 +242,14 @@ pub struct Miner {
sealing: Mutex<SealingWork>, sealing: Mutex<SealingWork>,
params: RwLock<AuthoringParams>, params: RwLock<AuthoringParams>,
#[cfg(feature = "work-notify")] #[cfg(feature = "work-notify")]
listeners: RwLock<Vec<Box<NotifyWork>>>, listeners: RwLock<Vec<Box<dyn NotifyWork>>>,
nonce_cache: NonceCache, nonce_cache: NonceCache,
gas_pricer: Mutex<GasPricer>, gas_pricer: Mutex<GasPricer>,
options: MinerOptions, options: MinerOptions,
// TODO [ToDr] Arc is only required because of price updater // TODO [ToDr] Arc is only required because of price updater
transaction_queue: Arc<TransactionQueue>, transaction_queue: Arc<TransactionQueue>,
engine: Arc<EthEngine>, engine: Arc<dyn EthEngine>,
accounts: Arc<LocalAccounts>, accounts: Arc<dyn LocalAccounts>,
io_channel: RwLock<Option<IoChannel<ClientIoMessage>>>, io_channel: RwLock<Option<IoChannel<ClientIoMessage>>>,
service_transaction_checker: Option<ServiceTransactionChecker>, service_transaction_checker: Option<ServiceTransactionChecker>,
} }
@ -257,13 +257,13 @@ pub struct Miner {
impl Miner { impl Miner {
/// Push listener that will handle new jobs /// Push listener that will handle new jobs
#[cfg(feature = "work-notify")] #[cfg(feature = "work-notify")]
pub fn add_work_listener(&self, notifier: Box<NotifyWork>) { pub fn add_work_listener(&self, notifier: Box<dyn NotifyWork>) {
self.listeners.write().push(notifier); self.listeners.write().push(notifier);
self.sealing.lock().enabled = true; self.sealing.lock().enabled = true;
} }
/// Set a callback to be notified about imported transactions' hashes. /// Set a callback to be notified about imported transactions' hashes.
pub fn add_transactions_listener(&self, f: Box<Fn(&[H256]) + Send + Sync>) { pub fn add_transactions_listener(&self, f: Box<dyn Fn(&[H256]) + Send + Sync>) {
self.transaction_queue.add_listener(f); self.transaction_queue.add_listener(f);
} }

View File

@ -66,8 +66,8 @@ impl NonceCache {
pub struct PoolClient<'a, C: 'a> { pub struct PoolClient<'a, C: 'a> {
chain: &'a C, chain: &'a C,
cached_nonces: CachedNonceClient<'a, C>, cached_nonces: CachedNonceClient<'a, C>,
engine: &'a EthEngine, engine: &'a dyn EthEngine,
accounts: &'a LocalAccounts, accounts: &'a dyn LocalAccounts,
best_block_header: Header, best_block_header: Header,
service_transaction_checker: Option<&'a ServiceTransactionChecker>, service_transaction_checker: Option<&'a ServiceTransactionChecker>,
} }
@ -93,8 +93,8 @@ where
pub fn new( pub fn new(
chain: &'a C, chain: &'a C,
cache: &'a NonceCache, cache: &'a NonceCache,
engine: &'a EthEngine, engine: &'a dyn EthEngine,
accounts: &'a LocalAccounts, accounts: &'a dyn LocalAccounts,
service_transaction_checker: Option<&'a ServiceTransactionChecker>, service_transaction_checker: Option<&'a ServiceTransactionChecker>,
) -> Self { ) -> Self {
let best_block_header = chain.best_block_header(); let best_block_header = chain.best_block_header();

View File

@ -263,7 +263,7 @@ impl Stratum {
#[cfg(feature = "work-notify")] #[cfg(feature = "work-notify")]
pub fn register(cfg: &Options, miner: Arc<Miner>, client: Weak<Client>) -> Result<(), Error> { pub fn register(cfg: &Options, miner: Arc<Miner>, client: Weak<Client>) -> Result<(), Error> {
let stratum = Stratum::start(cfg, Arc::downgrade(&miner.clone()), client)?; let stratum = Stratum::start(cfg, Arc::downgrade(&miner.clone()), client)?;
miner.add_work_listener(Box::new(stratum) as Box<NotifyWork>); miner.add_work_listener(Box::new(stratum) as Box<dyn NotifyWork>);
Ok(()) Ok(())
} }
} }

View File

@ -94,7 +94,7 @@ impl PodAccount {
/// Place additional data into given hash DB. /// Place additional data into given hash DB.
pub fn insert_additional( pub fn insert_additional(
&self, &self,
db: &mut HashDB<KeccakHasher, DBValue>, db: &mut dyn HashDB<KeccakHasher, DBValue>,
factory: &TrieFactory<KeccakHasher, RlpCodec>, factory: &TrieFactory<KeccakHasher, RlpCodec>,
) { ) {
match self.code { match self.code {

View File

@ -131,9 +131,9 @@ impl SnapshotComponents for PoaSnapshot {
fn rebuilder( fn rebuilder(
&self, &self,
chain: BlockChain, chain: BlockChain,
db: Arc<BlockChainDB>, db: Arc<dyn BlockChainDB>,
manifest: &ManifestData, manifest: &ManifestData,
) -> Result<Box<Rebuilder>, ::error::Error> { ) -> Result<Box<dyn Rebuilder>, ::error::Error> {
Ok(Box::new(ChunkRebuilder { Ok(Box::new(ChunkRebuilder {
manifest: manifest.clone(), manifest: manifest.clone(),
warp_target: None, warp_target: None,
@ -172,14 +172,14 @@ struct ChunkRebuilder {
manifest: ManifestData, manifest: ManifestData,
warp_target: Option<Header>, warp_target: Option<Header>,
chain: BlockChain, chain: BlockChain,
db: Arc<KeyValueDB>, db: Arc<dyn KeyValueDB>,
had_genesis: bool, had_genesis: bool,
// sorted vectors of unverified first blocks in a chunk // sorted vectors of unverified first blocks in a chunk
// and epoch data from last blocks in chunks. // and epoch data from last blocks in chunks.
// verification for these will be done at the end. // verification for these will be done at the end.
unverified_firsts: Vec<(Header, Bytes, H256)>, unverified_firsts: Vec<(Header, Bytes, H256)>,
last_epochs: Vec<(Header, Box<EpochVerifier<EthereumMachine>>)>, last_epochs: Vec<(Header, Box<dyn EpochVerifier<EthereumMachine>>)>,
} }
// verified data. // verified data.
@ -191,9 +191,9 @@ struct Verified {
impl ChunkRebuilder { impl ChunkRebuilder {
fn verify_transition( fn verify_transition(
&mut self, &mut self,
last_verifier: &mut Option<Box<EpochVerifier<EthereumMachine>>>, last_verifier: &mut Option<Box<dyn EpochVerifier<EthereumMachine>>>,
transition_rlp: Rlp, transition_rlp: Rlp,
engine: &EthEngine, engine: &dyn EthEngine,
) -> Result<Verified, ::error::Error> { ) -> Result<Verified, ::error::Error> {
use engines::ConstructedVerifier; use engines::ConstructedVerifier;
@ -253,7 +253,7 @@ impl Rebuilder for ChunkRebuilder {
fn feed( fn feed(
&mut self, &mut self,
chunk: &[u8], chunk: &[u8],
engine: &EthEngine, engine: &dyn EthEngine,
abort_flag: &AtomicBool, abort_flag: &AtomicBool,
) -> Result<(), ::error::Error> { ) -> Result<(), ::error::Error> {
let rlp = Rlp::new(chunk); let rlp = Rlp::new(chunk);
@ -384,7 +384,7 @@ impl Rebuilder for ChunkRebuilder {
Ok(()) Ok(())
} }
fn finalize(&mut self, _engine: &EthEngine) -> Result<(), ::error::Error> { fn finalize(&mut self, _engine: &dyn EthEngine) -> Result<(), ::error::Error> {
if !self.had_genesis { if !self.had_genesis {
return Err(Error::WrongChunkFormat("No genesis transition included.".into()).into()); return Err(Error::WrongChunkFormat("No genesis transition included.".into()).into());
} }

View File

@ -31,7 +31,7 @@ mod work;
pub use self::{authority::*, work::*}; pub use self::{authority::*, work::*};
/// A sink for produced chunks. /// 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. /// Components necessary for snapshot creation and restoration.
pub trait SnapshotComponents: Send { pub trait SnapshotComponents: Send {
@ -61,9 +61,9 @@ pub trait SnapshotComponents: Send {
fn rebuilder( fn rebuilder(
&self, &self,
chain: BlockChain, chain: BlockChain,
db: Arc<BlockChainDB>, db: Arc<dyn BlockChainDB>,
manifest: &ManifestData, manifest: &ManifestData,
) -> Result<Box<Rebuilder>, ::error::Error>; ) -> Result<Box<dyn Rebuilder>, ::error::Error>;
/// Minimum supported snapshot version number. /// Minimum supported snapshot version number.
fn min_supported_version(&self) -> u64; fn min_supported_version(&self) -> u64;
@ -81,7 +81,7 @@ pub trait Rebuilder: Send {
fn feed( fn feed(
&mut self, &mut self,
chunk: &[u8], chunk: &[u8],
engine: &EthEngine, engine: &dyn EthEngine,
abort_flag: &AtomicBool, abort_flag: &AtomicBool,
) -> Result<(), ::error::Error>; ) -> Result<(), ::error::Error>;
@ -90,5 +90,5 @@ pub trait Rebuilder: Send {
/// ///
/// This should apply the necessary "glue" between chunks, /// This should apply the necessary "glue" between chunks,
/// and verify against the restored state. /// 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>;
} }

View File

@ -85,9 +85,9 @@ impl SnapshotComponents for PowSnapshot {
fn rebuilder( fn rebuilder(
&self, &self,
chain: BlockChain, chain: BlockChain,
db: Arc<BlockChainDB>, db: Arc<dyn BlockChainDB>,
manifest: &ManifestData, manifest: &ManifestData,
) -> Result<Box<Rebuilder>, ::error::Error> { ) -> Result<Box<dyn Rebuilder>, ::error::Error> {
PowRebuilder::new( PowRebuilder::new(
chain, chain,
db.key_value().clone(), db.key_value().clone(),
@ -221,7 +221,7 @@ impl<'a> PowWorker<'a> {
/// After all chunks have been submitted, we "glue" the chunks together. /// After all chunks have been submitted, we "glue" the chunks together.
pub struct PowRebuilder { pub struct PowRebuilder {
chain: BlockChain, chain: BlockChain,
db: Arc<KeyValueDB>, db: Arc<dyn KeyValueDB>,
rng: OsRng, rng: OsRng,
disconnected: Vec<(u64, H256)>, disconnected: Vec<(u64, H256)>,
best_number: u64, best_number: u64,
@ -235,7 +235,7 @@ impl PowRebuilder {
/// Create a new PowRebuilder. /// Create a new PowRebuilder.
fn new( fn new(
chain: BlockChain, chain: BlockChain,
db: Arc<KeyValueDB>, db: Arc<dyn KeyValueDB>,
manifest: &ManifestData, manifest: &ManifestData,
snapshot_blocks: u64, snapshot_blocks: u64,
) -> Result<Self, ::error::Error> { ) -> Result<Self, ::error::Error> {
@ -259,7 +259,7 @@ impl Rebuilder for PowRebuilder {
fn feed( fn feed(
&mut self, &mut self,
chunk: &[u8], chunk: &[u8],
engine: &EthEngine, engine: &dyn EthEngine,
abort_flag: &AtomicBool, abort_flag: &AtomicBool,
) -> Result<(), ::error::Error> { ) -> Result<(), ::error::Error> {
use ethereum_types::U256; use ethereum_types::U256;
@ -354,7 +354,7 @@ impl Rebuilder for PowRebuilder {
} }
/// Glue together any disconnected chunks and check that the chain is complete. /// 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(); let mut batch = self.db.transaction();
for (first_num, first_hash) in self.disconnected.drain(..) { for (first_num, first_hash) in self.disconnected.drain(..) {

View File

@ -88,22 +88,22 @@ struct Restoration {
state_chunks_left: HashSet<H256>, state_chunks_left: HashSet<H256>,
block_chunks_left: HashSet<H256>, block_chunks_left: HashSet<H256>,
state: StateRebuilder, state: StateRebuilder,
secondary: Box<Rebuilder>, secondary: Box<dyn Rebuilder>,
writer: Option<LooseWriter>, writer: Option<LooseWriter>,
snappy_buffer: Bytes, snappy_buffer: Bytes,
final_state_root: H256, final_state_root: H256,
guard: Guard, guard: Guard,
db: Arc<BlockChainDB>, db: Arc<dyn BlockChainDB>,
} }
struct RestorationParams<'a> { struct RestorationParams<'a> {
manifest: ManifestData, // manifest to base restoration on. manifest: ManifestData, // manifest to base restoration on.
pruning: Algorithm, // pruning algorithm for the database. pruning: Algorithm, // pruning algorithm for the database.
db: Arc<BlockChainDB>, // database db: Arc<dyn BlockChainDB>, // database
writer: Option<LooseWriter>, // writer for recovered snapshot. writer: Option<LooseWriter>, // writer for recovered snapshot.
genesis: &'a [u8], // genesis block of the chain. genesis: &'a [u8], // genesis block of the chain.
guard: Guard, // guard for the restoration directory. guard: Guard, // guard for the restoration directory.
engine: &'a EthEngine, engine: &'a dyn EthEngine,
} }
impl Restoration { impl Restoration {
@ -167,7 +167,7 @@ impl Restoration {
&mut self, &mut self,
hash: H256, hash: H256,
chunk: &[u8], chunk: &[u8],
engine: &EthEngine, engine: &dyn EthEngine,
flag: &AtomicBool, flag: &AtomicBool,
) -> Result<(), Error> { ) -> Result<(), Error> {
if self.block_chunks_left.contains(&hash) { if self.block_chunks_left.contains(&hash) {
@ -191,7 +191,7 @@ impl Restoration {
} }
// finish up restoration. // finish up restoration.
fn finalize(mut self, engine: &EthEngine) -> Result<(), Error> { fn finalize(mut self, engine: &dyn EthEngine) -> Result<(), Error> {
use trie::TrieError; use trie::TrieError;
if !self.is_done() { if !self.is_done() {
@ -238,37 +238,37 @@ pub trait SnapshotClient: BlockChainClient + BlockInfo + DatabaseRestore {}
/// Snapshot service parameters. /// Snapshot service parameters.
pub struct ServiceParams { pub struct ServiceParams {
/// The consensus engine this is built on. /// The consensus engine this is built on.
pub engine: Arc<EthEngine>, pub engine: Arc<dyn EthEngine>,
/// The chain's genesis block. /// The chain's genesis block.
pub genesis_block: Bytes, pub genesis_block: Bytes,
/// State pruning algorithm. /// State pruning algorithm.
pub pruning: Algorithm, pub pruning: Algorithm,
/// Handler for opening a restoration DB. /// Handler for opening a restoration DB.
pub restoration_db_handler: Box<BlockChainDBHandler>, pub restoration_db_handler: Box<dyn BlockChainDBHandler>,
/// Async IO channel for sending messages. /// Async IO channel for sending messages.
pub channel: Channel, pub channel: Channel,
/// The directory to put snapshots in. /// The directory to put snapshots in.
/// Usually "<chain hash>/snapshot" /// Usually "<chain hash>/snapshot"
pub snapshot_root: PathBuf, pub snapshot_root: PathBuf,
/// A handle for database restoration. /// A handle for database restoration.
pub client: Arc<SnapshotClient>, pub client: Arc<dyn SnapshotClient>,
} }
/// `SnapshotService` implementation. /// `SnapshotService` implementation.
/// This controls taking snapshots and restoring from them. /// This controls taking snapshots and restoring from them.
pub struct Service { pub struct Service {
restoration: Mutex<Option<Restoration>>, restoration: Mutex<Option<Restoration>>,
restoration_db_handler: Box<BlockChainDBHandler>, restoration_db_handler: Box<dyn BlockChainDBHandler>,
snapshot_root: PathBuf, snapshot_root: PathBuf,
io_channel: Mutex<Channel>, io_channel: Mutex<Channel>,
pruning: Algorithm, pruning: Algorithm,
status: Mutex<RestorationStatus>, status: Mutex<RestorationStatus>,
reader: RwLock<Option<LooseReader>>, reader: RwLock<Option<LooseReader>>,
engine: Arc<EthEngine>, engine: Arc<dyn EthEngine>,
genesis_block: Bytes, genesis_block: Bytes,
state_chunks: AtomicUsize, state_chunks: AtomicUsize,
block_chunks: AtomicUsize, block_chunks: AtomicUsize,
client: Arc<SnapshotClient>, client: Arc<dyn SnapshotClient>,
progress: super::Progress, progress: super::Progress,
taking_snapshot: AtomicBool, taking_snapshot: AtomicBool,
restoring_snapshot: AtomicBool, restoring_snapshot: AtomicBool,

View File

@ -64,7 +64,7 @@ impl StateProducer {
/// Tick the state producer. This alters the state, writing new data into /// Tick the state producer. This alters the state, writing new data into
/// the database. /// the database.
pub fn tick<R: Rng>(&mut self, rng: &mut R, db: &mut HashDB<KeccakHasher, DBValue>) { pub fn tick<R: Rng>(&mut self, rng: &mut R, db: &mut dyn HashDB<KeccakHasher, DBValue>) {
// modify existing accounts. // modify existing accounts.
let mut accounts_to_modify: Vec<_> = { let mut accounts_to_modify: Vec<_> = {
let trie = TrieDB::new(&db, &self.state_root).unwrap(); 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. /// Take a snapshot from the given client into a temporary file.
/// Return a snapshot reader for it. /// Return a snapshot reader for it.
pub fn snap(client: &Client) -> (Box<SnapshotReader>, TempDir) { pub fn snap(client: &Client) -> (Box<dyn SnapshotReader>, TempDir) {
use types::ids::BlockId; use types::ids::BlockId;
let tempdir = TempDir::new("").unwrap(); let tempdir = TempDir::new("").unwrap();
@ -158,9 +158,9 @@ pub fn snap(client: &Client) -> (Box<SnapshotReader>, TempDir) {
/// Restore a snapshot into a given database. This will read chunks from the given reader /// Restore a snapshot into a given database. This will read chunks from the given reader
/// write into the given database. /// write into the given database.
pub fn restore( pub fn restore(
db: Arc<BlockChainDB>, db: Arc<dyn BlockChainDB>,
engine: &EthEngine, engine: &dyn EthEngine,
reader: &SnapshotReader, reader: &dyn SnapshotReader,
genesis: &[u8], genesis: &[u8],
) -> Result<(), ::error::Error> { ) -> Result<(), ::error::Error> {
use snappy; use snappy;

View File

@ -78,8 +78,8 @@ impl Broadcast for Mutex<IoChannel<ClientIoMessage>> {
/// A `ChainNotify` implementation which will trigger a snapshot event /// A `ChainNotify` implementation which will trigger a snapshot event
/// at certain block numbers. /// at certain block numbers.
pub struct Watcher { pub struct Watcher {
oracle: Box<Oracle>, oracle: Box<dyn Oracle>,
broadcast: Box<Broadcast>, broadcast: Box<dyn Broadcast>,
period: u64, period: u64,
history: u64, history: u64,
} }

View File

@ -402,7 +402,7 @@ pub struct Spec {
/// User friendly spec name /// User friendly spec name
pub name: String, pub name: String,
/// What engine are we using for this? /// What engine are we using for this?
pub engine: Arc<EthEngine>, pub engine: Arc<dyn EthEngine>,
/// Name of the subdir inside the main data dir to use for chain data and settings. /// Name of the subdir inside the main data dir to use for chain data and settings.
pub data_dir: String, pub data_dir: String,
@ -642,7 +642,7 @@ impl Spec {
engine_spec: ethjson::spec::Engine, engine_spec: ethjson::spec::Engine,
params: CommonParams, params: CommonParams,
builtins: BTreeMap<Address, Builtin>, builtins: BTreeMap<Address, Builtin>,
) -> Arc<EthEngine> { ) -> Arc<dyn EthEngine> {
let machine = Self::machine(&engine_spec, params, builtins); let machine = Self::machine(&engine_spec, params, builtins);
match engine_spec { match engine_spec {

View File

@ -225,7 +225,11 @@ impl Account {
/// Get (and cache) the contents of the trie's storage at `key`. /// Get (and cache) the contents of the trie's storage at `key`.
/// Takes modified storage into account. /// Takes modified storage into account.
pub fn storage_at(&self, db: &HashDB<KeccakHasher, DBValue>, key: &H256) -> TrieResult<H256> { pub fn storage_at(
&self,
db: &dyn HashDB<KeccakHasher, DBValue>,
key: &H256,
) -> TrieResult<H256> {
if let Some(value) = self.cached_storage_at(key) { if let Some(value) = self.cached_storage_at(key) {
return Ok(value); return Ok(value);
} }
@ -241,7 +245,7 @@ impl Account {
/// Does not take modified storage into account. /// Does not take modified storage into account.
pub fn original_storage_at( pub fn original_storage_at(
&self, &self,
db: &HashDB<KeccakHasher, DBValue>, db: &dyn HashDB<KeccakHasher, DBValue>,
key: &H256, key: &H256,
) -> TrieResult<H256> { ) -> TrieResult<H256> {
if let Some(value) = self.cached_original_storage_at(key) { if let Some(value) = self.cached_original_storage_at(key) {
@ -268,7 +272,7 @@ impl Account {
fn get_and_cache_storage( fn get_and_cache_storage(
storage_root: &H256, storage_root: &H256,
storage_cache: &mut LruCache<H256, H256>, storage_cache: &mut LruCache<H256, H256>,
db: &HashDB<KeccakHasher, DBValue>, db: &dyn HashDB<KeccakHasher, DBValue>,
key: &H256, key: &H256,
) -> TrieResult<H256> { ) -> TrieResult<H256> {
let db = SecTrieDB::new(&db, storage_root)?; 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. /// 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] #[must_use]
pub fn cache_code(&mut self, db: &HashDB<KeccakHasher, DBValue>) -> Option<Arc<Bytes>> { pub fn cache_code(&mut self, db: &dyn HashDB<KeccakHasher, DBValue>) -> Option<Arc<Bytes>> {
// TODO: fill out self.code_cache; // TODO: fill out self.code_cache;
trace!( trace!(
"Account::cache_code: ic={}; self.code_hash={:?}, self.code_cache={}", "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 /// Provide a database to get `code_size`. Should not be called if it is a contract without code. Returns whether
/// the cache succeeds. /// the cache succeeds.
#[must_use] #[must_use]
pub fn cache_code_size(&mut self, db: &HashDB<KeccakHasher, DBValue>) -> bool { pub fn cache_code_size(&mut self, db: &dyn HashDB<KeccakHasher, DBValue>) -> bool {
// TODO: fill out self.code_cache; // TODO: fill out self.code_cache;
trace!( trace!(
"Account::cache_code_size: ic={}; self.code_hash={:?}, self.code_cache={}", "Account::cache_code_size: ic={}; self.code_hash={:?}, self.code_cache={}",
@ -531,7 +535,7 @@ impl Account {
pub fn commit_storage( pub fn commit_storage(
&mut self, &mut self,
trie_factory: &TrieFactory, trie_factory: &TrieFactory,
db: &mut HashDB<KeccakHasher, DBValue>, db: &mut dyn HashDB<KeccakHasher, DBValue>,
) -> TrieResult<()> { ) -> TrieResult<()> {
let mut t = trie_factory.from_existing(db, &mut self.storage_root)?; let mut t = trie_factory.from_existing(db, &mut self.storage_root)?;
for (k, v) in self.storage_changes.drain() { 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. /// 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<KeccakHasher, DBValue>) { pub fn commit_code(&mut self, db: &mut dyn HashDB<KeccakHasher, DBValue>) {
trace!( trace!(
"Commiting code of {:?} - {:?}, {:?}", "Commiting code of {:?} - {:?}, {:?}",
self, self,
@ -651,7 +655,7 @@ impl Account {
/// this will only work correctly under a secure trie. /// this will only work correctly under a secure trie.
pub fn prove_storage( pub fn prove_storage(
&self, &self,
db: &HashDB<KeccakHasher, DBValue>, db: &dyn HashDB<KeccakHasher, DBValue>,
storage_key: H256, storage_key: H256,
) -> TrieResult<(Vec<Bytes>, H256)> { ) -> TrieResult<(Vec<Bytes>, H256)> {
let mut recorder = Recorder::new(); let mut recorder = Recorder::new();

View File

@ -38,10 +38,10 @@ use state::Account;
/// State backend. See module docs for more details. /// State backend. See module docs for more details.
pub trait Backend: Send { pub trait Backend: Send {
/// Treat the backend as a read-only hashdb. /// Treat the backend as a read-only hashdb.
fn as_hash_db(&self) -> &HashDB<KeccakHasher, DBValue>; fn as_hash_db(&self) -> &dyn HashDB<KeccakHasher, DBValue>;
/// Treat the backend as a writeable hashdb. /// Treat the backend as a writeable hashdb.
fn as_hash_db_mut(&mut self) -> &mut HashDB<KeccakHasher, DBValue>; fn as_hash_db_mut(&mut self) -> &mut dyn HashDB<KeccakHasher, DBValue>;
/// Add an account entry to the cache. /// Add an account entry to the cache.
fn add_to_account_cache(&mut self, addr: Address, data: Option<Account>, modified: bool); fn add_to_account_cache(&mut self, addr: Address, data: Option<Account>, modified: bool);
@ -121,19 +121,19 @@ impl HashDB<KeccakHasher, DBValue> for ProofCheck {
} }
impl AsHashDB<KeccakHasher, DBValue> for ProofCheck { impl AsHashDB<KeccakHasher, DBValue> for ProofCheck {
fn as_hash_db(&self) -> &HashDB<KeccakHasher, DBValue> { fn as_hash_db(&self) -> &dyn HashDB<KeccakHasher, DBValue> {
self self
} }
fn as_hash_db_mut(&mut self) -> &mut HashDB<KeccakHasher, DBValue> { fn as_hash_db_mut(&mut self) -> &mut dyn HashDB<KeccakHasher, DBValue> {
self self
} }
} }
impl Backend for ProofCheck { impl Backend for ProofCheck {
fn as_hash_db(&self) -> &HashDB<KeccakHasher, DBValue> { fn as_hash_db(&self) -> &dyn HashDB<KeccakHasher, DBValue> {
self self
} }
fn as_hash_db_mut(&mut self) -> &mut HashDB<KeccakHasher, DBValue> { fn as_hash_db_mut(&mut self) -> &mut dyn HashDB<KeccakHasher, DBValue> {
self self
} }
fn add_to_account_cache(&mut self, _addr: Address, _data: Option<Account>, _modified: bool) {} fn add_to_account_cache(&mut self, _addr: Address, _data: Option<Account>, _modified: bool) {}
@ -168,7 +168,7 @@ pub struct Proving<H> {
} }
impl<AH: AsKeyedHashDB + Send + Sync> AsKeyedHashDB for Proving<AH> { impl<AH: AsKeyedHashDB + Send + Sync> AsKeyedHashDB for Proving<AH> {
fn as_keyed_hash_db(&self) -> &journaldb::KeyedHashDB { fn as_keyed_hash_db(&self) -> &dyn journaldb::KeyedHashDB {
self self
} }
} }
@ -176,10 +176,10 @@ impl<AH: AsKeyedHashDB + Send + Sync> AsKeyedHashDB for Proving<AH> {
impl<AH: AsHashDB<KeccakHasher, DBValue> + Send + Sync> AsHashDB<KeccakHasher, DBValue> impl<AH: AsHashDB<KeccakHasher, DBValue> + Send + Sync> AsHashDB<KeccakHasher, DBValue>
for Proving<AH> for Proving<AH>
{ {
fn as_hash_db(&self) -> &HashDB<KeccakHasher, DBValue> { fn as_hash_db(&self) -> &dyn HashDB<KeccakHasher, DBValue> {
self self
} }
fn as_hash_db_mut(&mut self) -> &mut HashDB<KeccakHasher, DBValue> { fn as_hash_db_mut(&mut self) -> &mut dyn HashDB<KeccakHasher, DBValue> {
self self
} }
} }
@ -226,11 +226,11 @@ impl<H: AsHashDB<KeccakHasher, DBValue> + Send + Sync> HashDB<KeccakHasher, DBVa
} }
impl<H: AsHashDB<KeccakHasher, DBValue> + Send + Sync> Backend for Proving<H> { impl<H: AsHashDB<KeccakHasher, DBValue> + Send + Sync> Backend for Proving<H> {
fn as_hash_db(&self) -> &HashDB<KeccakHasher, DBValue> { fn as_hash_db(&self) -> &dyn HashDB<KeccakHasher, DBValue> {
self self
} }
fn as_hash_db_mut(&mut self) -> &mut HashDB<KeccakHasher, DBValue> { fn as_hash_db_mut(&mut self) -> &mut dyn HashDB<KeccakHasher, DBValue> {
self self
} }
@ -291,11 +291,11 @@ impl<H: AsHashDB<KeccakHasher, DBValue> + Clone> Clone for Proving<H> {
pub struct Basic<H>(pub H); pub struct Basic<H>(pub H);
impl<H: AsHashDB<KeccakHasher, DBValue> + Send + Sync> Backend for Basic<H> { impl<H: AsHashDB<KeccakHasher, DBValue> + Send + Sync> Backend for Basic<H> {
fn as_hash_db(&self) -> &HashDB<KeccakHasher, DBValue> { fn as_hash_db(&self) -> &dyn HashDB<KeccakHasher, DBValue> {
self.0.as_hash_db() self.0.as_hash_db()
} }
fn as_hash_db_mut(&mut self) -> &mut HashDB<KeccakHasher, DBValue> { fn as_hash_db_mut(&mut self) -> &mut dyn HashDB<KeccakHasher, DBValue> {
self.0.as_hash_db_mut() self.0.as_hash_db_mut()
} }

View File

@ -702,7 +702,7 @@ impl<B: Backend> State<B> {
) -> TrieResult<H256> ) -> TrieResult<H256>
where where
FCachedStorageAt: Fn(&Account, &H256) -> Option<H256>, FCachedStorageAt: Fn(&Account, &H256) -> Option<H256>,
FStorageAt: Fn(&Account, &HashDB<KeccakHasher, DBValue>, &H256) -> TrieResult<H256>, FStorageAt: Fn(&Account, &dyn HashDB<KeccakHasher, DBValue>, &H256) -> TrieResult<H256>,
{ {
// Storage key search and update works like this: // 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. // 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<B: Backend> State<B> {
require: RequireCache, require: RequireCache,
account: &mut Account, account: &mut Account,
state_db: &B, state_db: &B,
db: &HashDB<KeccakHasher, DBValue>, db: &dyn HashDB<KeccakHasher, DBValue>,
) -> bool { ) -> bool {
if let RequireCache::None = require { if let RequireCache::None = require {
return true; return true;

View File

@ -109,7 +109,7 @@ struct BlockChanges {
/// `StateDB` is propagated into the global cache. /// `StateDB` is propagated into the global cache.
pub struct StateDB { pub struct StateDB {
/// Backing database. /// Backing database.
db: Box<JournalDB>, db: Box<dyn JournalDB>,
/// Shared canonical state cache. /// Shared canonical state cache.
account_cache: Arc<Mutex<AccountCache>>, account_cache: Arc<Mutex<AccountCache>>,
/// DB Code cache. Maps code hashes to shared bytes. /// 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. /// 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 // TODO: make the cache size actually accurate by moving the account storage cache
// into the `AccountCache` structure as its own `LruCache<(Address, H256), H256>`. // into the `AccountCache` structure as its own `LruCache<(Address, H256), H256>`.
pub fn new(db: Box<JournalDB>, cache_size: usize) -> StateDB { pub fn new(db: Box<dyn JournalDB>, cache_size: usize) -> StateDB {
let bloom = Self::load_bloom(&**db.backing()); let bloom = Self::load_bloom(&**db.backing());
let acc_cache_size = cache_size * ACCOUNT_CACHE_RATIO / 100; let acc_cache_size = cache_size * ACCOUNT_CACHE_RATIO / 100;
let code_cache_size = cache_size - acc_cache_size; let code_cache_size = cache_size - acc_cache_size;
@ -157,7 +157,7 @@ impl StateDB {
/// Loads accounts bloom from the database /// Loads accounts bloom from the database
/// This bloom is used to handle request for the non-existant account fast /// 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 let hash_count_entry = db
.get(COL_ACCOUNT_BLOOM, ACCOUNT_BLOOM_HASHCOUNT_KEY) .get(COL_ACCOUNT_BLOOM, ACCOUNT_BLOOM_HASHCOUNT_KEY)
.expect("Low-level database error"); .expect("Low-level database error");
@ -349,12 +349,12 @@ impl StateDB {
} }
/// Conversion method to interpret self as `HashDB` reference /// Conversion method to interpret self as `HashDB` reference
pub fn as_hash_db(&self) -> &HashDB<KeccakHasher, DBValue> { pub fn as_hash_db(&self) -> &dyn HashDB<KeccakHasher, DBValue> {
self.db.as_hash_db() self.db.as_hash_db()
} }
/// Conversion method to interpret self as mutable `HashDB` reference /// Conversion method to interpret self as mutable `HashDB` reference
pub fn as_hash_db_mut(&mut self) -> &mut HashDB<KeccakHasher, DBValue> { pub fn as_hash_db_mut(&mut self) -> &mut dyn HashDB<KeccakHasher, DBValue> {
self.db.as_hash_db_mut() self.db.as_hash_db_mut()
} }
@ -404,7 +404,7 @@ impl StateDB {
} }
/// Returns underlying `JournalDB`. /// Returns underlying `JournalDB`.
pub fn journal_db(&self) -> &JournalDB { pub fn journal_db(&self) -> &dyn JournalDB {
&*self.db &*self.db
} }
@ -453,11 +453,11 @@ impl StateDB {
} }
impl state::Backend for StateDB { impl state::Backend for StateDB {
fn as_hash_db(&self) -> &HashDB<KeccakHasher, DBValue> { fn as_hash_db(&self) -> &dyn HashDB<KeccakHasher, DBValue> {
self.db.as_hash_db() self.db.as_hash_db()
} }
fn as_hash_db_mut(&mut self) -> &mut HashDB<KeccakHasher, DBValue> { fn as_hash_db_mut(&mut self) -> &mut dyn HashDB<KeccakHasher, DBValue> {
self.db.as_hash_db_mut() self.db.as_hash_db_mut()
} }

View File

@ -333,11 +333,11 @@ struct TestBlockChainDB {
_trace_blooms_dir: TempDir, _trace_blooms_dir: TempDir,
blooms: blooms_db::Database, blooms: blooms_db::Database,
trace_blooms: blooms_db::Database, trace_blooms: blooms_db::Database,
key_value: Arc<KeyValueDB>, key_value: Arc<dyn KeyValueDB>,
} }
impl BlockChainDB for TestBlockChainDB { impl BlockChainDB for TestBlockChainDB {
fn key_value(&self) -> &Arc<KeyValueDB> { fn key_value(&self) -> &Arc<dyn KeyValueDB> {
&self.key_value &self.key_value
} }
@ -351,7 +351,7 @@ impl BlockChainDB for TestBlockChainDB {
} }
/// Creates new test instance of `BlockChainDB` /// Creates new test instance of `BlockChainDB`
pub fn new_db() -> Arc<BlockChainDB> { pub fn new_db() -> Arc<dyn BlockChainDB> {
let blooms_dir = TempDir::new("").unwrap(); let blooms_dir = TempDir::new("").unwrap();
let trace_blooms_dir = TempDir::new("").unwrap(); let trace_blooms_dir = TempDir::new("").unwrap();
@ -367,7 +367,7 @@ pub fn new_db() -> Arc<BlockChainDB> {
} }
/// Creates a new temporary `BlockChainDB` on FS /// Creates a new temporary `BlockChainDB` on FS
pub fn new_temp_db(tempdir: &Path) -> Arc<BlockChainDB> { pub fn new_temp_db(tempdir: &Path) -> Arc<dyn BlockChainDB> {
let blooms_dir = TempDir::new("").unwrap(); let blooms_dir = TempDir::new("").unwrap();
let trace_blooms_dir = TempDir::new("").unwrap(); let trace_blooms_dir = TempDir::new("").unwrap();
let key_value_dir = tempdir.join("key_value"); let key_value_dir = tempdir.join("key_value");
@ -387,7 +387,9 @@ pub fn new_temp_db(tempdir: &Path) -> Arc<BlockChainDB> {
} }
/// Creates new instance of KeyValueDBHandler /// Creates new instance of KeyValueDBHandler
pub fn restoration_db_handler(config: kvdb_rocksdb::DatabaseConfig) -> Box<BlockChainDBHandler> { pub fn restoration_db_handler(
config: kvdb_rocksdb::DatabaseConfig,
) -> Box<dyn BlockChainDBHandler> {
struct RestorationDBHandler { struct RestorationDBHandler {
config: kvdb_rocksdb::DatabaseConfig, config: kvdb_rocksdb::DatabaseConfig,
} }
@ -395,11 +397,11 @@ pub fn restoration_db_handler(config: kvdb_rocksdb::DatabaseConfig) -> Box<Block
struct RestorationDB { struct RestorationDB {
blooms: blooms_db::Database, blooms: blooms_db::Database,
trace_blooms: blooms_db::Database, trace_blooms: blooms_db::Database,
key_value: Arc<KeyValueDB>, key_value: Arc<dyn KeyValueDB>,
} }
impl BlockChainDB for RestorationDB { impl BlockChainDB for RestorationDB {
fn key_value(&self) -> &Arc<KeyValueDB> { fn key_value(&self) -> &Arc<dyn KeyValueDB> {
&self.key_value &self.key_value
} }
@ -413,7 +415,7 @@ pub fn restoration_db_handler(config: kvdb_rocksdb::DatabaseConfig) -> Box<Block
} }
impl BlockChainDBHandler for RestorationDBHandler { impl BlockChainDBHandler for RestorationDBHandler {
fn open(&self, db_path: &Path) -> io::Result<Arc<BlockChainDB>> { fn open(&self, db_path: &Path) -> io::Result<Arc<dyn BlockChainDB>> {
let key_value = Arc::new(kvdb_rocksdb::Database::open( let key_value = Arc::new(kvdb_rocksdb::Database::open(
&self.config, &self.config,
&db_path.to_string_lossy(), &db_path.to_string_lossy(),

View File

@ -64,7 +64,7 @@ where
/// hashes of cached traces /// hashes of cached traces
cache_manager: RwLock<CacheManager<H256>>, cache_manager: RwLock<CacheManager<H256>>,
/// db /// db
db: Arc<BlockChainDB>, db: Arc<dyn BlockChainDB>,
/// tracing enabled /// tracing enabled
enabled: bool, enabled: bool,
/// extras /// extras
@ -76,7 +76,7 @@ where
T: DatabaseExtras, T: DatabaseExtras,
{ {
/// Creates new instance of `TraceDB`. /// Creates new instance of `TraceDB`.
pub fn new(config: Config, db: Arc<BlockChainDB>, extras: Arc<T>) -> Self { pub fn new(config: Config, db: Arc<dyn BlockChainDB>, extras: Arc<T>) -> Self {
let mut batch = DBTransaction::new(); let mut batch = DBTransaction::new();
let genesis = extras let genesis = extras
.block_hash(0) .block_hash(0)

View File

@ -31,7 +31,7 @@ impl<C: BlockInfo + CallContract> Verifier<C> for CanonVerifier {
&self, &self,
header: &Header, header: &Header,
parent: &Header, parent: &Header,
engine: &EthEngine, engine: &dyn EthEngine,
do_full: Option<verification::FullFamilyParams<C>>, do_full: Option<verification::FullFamilyParams<C>>,
) -> Result<(), Error> { ) -> Result<(), Error> {
verification::verify_block_family(header, parent, engine, do_full) verification::verify_block_family(header, parent, engine, do_full)
@ -41,7 +41,7 @@ impl<C: BlockInfo + CallContract> Verifier<C> for CanonVerifier {
verification::verify_block_final(expected, got) 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) engine.verify_block_external(header)
} }
} }

View File

@ -46,7 +46,7 @@ pub enum VerifierType {
} }
/// Create a new verifier based on type. /// Create a new verifier based on type.
pub fn new<C: BlockInfo + CallContract>(v: VerifierType) -> Box<Verifier<C>> { pub fn new<C: BlockInfo + CallContract>(v: VerifierType) -> Box<dyn Verifier<C>> {
match v { match v {
VerifierType::Canon | VerifierType::CanonNoSeal => Box::new(CanonVerifier), VerifierType::Canon | VerifierType::CanonNoSeal => Box::new(CanonVerifier),
VerifierType::Noop => Box::new(NoopVerifier), VerifierType::Noop => Box::new(NoopVerifier),

View File

@ -32,7 +32,7 @@ impl<C: BlockInfo + CallContract> Verifier<C> for NoopVerifier {
&self, &self,
_: &Header, _: &Header,
_t: &Header, _t: &Header,
_: &EthEngine, _: &dyn EthEngine,
_: Option<verification::FullFamilyParams<C>>, _: Option<verification::FullFamilyParams<C>>,
) -> Result<(), Error> { ) -> Result<(), Error> {
Ok(()) Ok(())
@ -42,7 +42,11 @@ impl<C: BlockInfo + CallContract> Verifier<C> for NoopVerifier {
Ok(()) 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(()) Ok(())
} }
} }

View File

@ -62,14 +62,14 @@ pub trait Kind: 'static + Sized + Send + Sync {
/// Attempt to create the `Unverified` item from the input. /// Attempt to create the `Unverified` item from the input.
fn create( fn create(
input: Self::Input, input: Self::Input,
engine: &EthEngine, engine: &dyn EthEngine,
check_seal: bool, check_seal: bool,
) -> Result<Self::Unverified, (Self::Input, Error)>; ) -> Result<Self::Unverified, (Self::Input, Error)>;
/// Attempt to verify the `Unverified` item using the given engine. /// Attempt to verify the `Unverified` item using the given engine.
fn verify( fn verify(
unverified: Self::Unverified, unverified: Self::Unverified,
engine: &EthEngine, engine: &dyn EthEngine,
check_seal: bool, check_seal: bool,
) -> Result<Self::Verified, Error>; ) -> Result<Self::Verified, Error>;
} }
@ -97,7 +97,7 @@ pub mod blocks {
fn create( fn create(
input: Self::Input, input: Self::Input,
engine: &EthEngine, engine: &dyn EthEngine,
check_seal: bool, check_seal: bool,
) -> Result<Self::Unverified, (Self::Input, Error)> { ) -> Result<Self::Unverified, (Self::Input, Error)> {
match verify_block_basic(&input, engine, check_seal) { match verify_block_basic(&input, engine, check_seal) {
@ -115,7 +115,7 @@ pub mod blocks {
fn verify( fn verify(
un: Self::Unverified, un: Self::Unverified,
engine: &EthEngine, engine: &dyn EthEngine,
check_seal: bool, check_seal: bool,
) -> Result<Self::Verified, Error> { ) -> Result<Self::Verified, Error> {
let hash = un.hash(); let hash = un.hash();
@ -245,7 +245,7 @@ pub mod headers {
fn create( fn create(
input: Self::Input, input: Self::Input,
engine: &EthEngine, engine: &dyn EthEngine,
check_seal: bool, check_seal: bool,
) -> Result<Self::Unverified, (Self::Input, Error)> { ) -> Result<Self::Unverified, (Self::Input, Error)> {
match verify_header_params(&input, engine, true, check_seal) { match verify_header_params(&input, engine, true, check_seal) {
@ -256,7 +256,7 @@ pub mod headers {
fn verify( fn verify(
unverified: Self::Unverified, unverified: Self::Unverified,
engine: &EthEngine, engine: &dyn EthEngine,
check_seal: bool, check_seal: bool,
) -> Result<Self::Verified, Error> { ) -> Result<Self::Verified, Error> {
match check_seal { match check_seal {

View File

@ -142,7 +142,7 @@ struct Sizes {
/// A queue of items to be verified. Sits between network or other I/O and the `BlockChain`. /// 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. /// Keeps them in the same order as inserted, minus invalid items.
pub struct VerificationQueue<K: Kind> { pub struct VerificationQueue<K: Kind> {
engine: Arc<EthEngine>, engine: Arc<dyn EthEngine>,
more_to_verify: Arc<Condvar>, more_to_verify: Arc<Condvar>,
verification: Arc<Verification<K>>, verification: Arc<Verification<K>>,
deleting: Arc<AtomicBool>, deleting: Arc<AtomicBool>,
@ -220,7 +220,7 @@ impl<K: Kind> VerificationQueue<K> {
/// Creates a new queue instance. /// Creates a new queue instance.
pub fn new( pub fn new(
config: Config, config: Config,
engine: Arc<EthEngine>, engine: Arc<dyn EthEngine>,
message_channel: IoChannel<ClientIoMessage>, message_channel: IoChannel<ClientIoMessage>,
check_seal: bool, check_seal: bool,
) -> Self { ) -> Self {
@ -305,7 +305,7 @@ impl<K: Kind> VerificationQueue<K> {
fn verify( fn verify(
verification: Arc<Verification<K>>, verification: Arc<Verification<K>>,
engine: Arc<EthEngine>, engine: Arc<dyn EthEngine>,
wait: Arc<Condvar>, wait: Arc<Condvar>,
ready: Arc<QueueSignal>, ready: Arc<QueueSignal>,
empty: Arc<Condvar>, empty: Arc<Condvar>,

View File

@ -66,7 +66,7 @@ impl HeapSizeOf for PreverifiedBlock {
/// Phase 1 quick block verification. Only does checks that are cheap. Operates on a single block /// Phase 1 quick block verification. Only does checks that are cheap. Operates on a single block
pub fn verify_block_basic( pub fn verify_block_basic(
block: &Unverified, block: &Unverified,
engine: &EthEngine, engine: &dyn EthEngine,
check_seal: bool, check_seal: bool,
) -> Result<(), Error> { ) -> Result<(), Error> {
verify_header_params(&block.header, engine, true, check_seal)?; 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 /// Returns a `PreverifiedBlock` structure populated with transactions
pub fn verify_block_unordered( pub fn verify_block_unordered(
block: Unverified, block: Unverified,
engine: &EthEngine, engine: &dyn EthEngine,
check_seal: bool, check_seal: bool,
) -> Result<PreverifiedBlock, Error> { ) -> Result<PreverifiedBlock, Error> {
let header = block.header; let header = block.header;
@ -140,7 +140,7 @@ pub struct FullFamilyParams<'a, C: BlockInfo + CallContract + 'a> {
pub block: &'a PreverifiedBlock, pub block: &'a PreverifiedBlock,
/// Block provider to use during verification /// Block provider to use during verification
pub block_provider: &'a BlockProvider, pub block_provider: &'a dyn BlockProvider,
/// Engine client to use during verification /// Engine client to use during verification
pub client: &'a C, pub client: &'a C,
@ -150,7 +150,7 @@ pub struct FullFamilyParams<'a, C: BlockInfo + CallContract + 'a> {
pub fn verify_block_family<C: BlockInfo + CallContract>( pub fn verify_block_family<C: BlockInfo + CallContract>(
header: &Header, header: &Header,
parent: &Header, parent: &Header,
engine: &EthEngine, engine: &dyn EthEngine,
do_full: Option<FullFamilyParams<C>>, do_full: Option<FullFamilyParams<C>>,
) -> Result<(), Error> { ) -> Result<(), Error> {
// TODO: verify timestamp // TODO: verify timestamp
@ -177,8 +177,8 @@ pub fn verify_block_family<C: BlockInfo + CallContract>(
fn verify_uncles( fn verify_uncles(
block: &PreverifiedBlock, block: &PreverifiedBlock,
bc: &BlockProvider, bc: &dyn BlockProvider,
engine: &EthEngine, engine: &dyn EthEngine,
) -> Result<(), Error> { ) -> Result<(), Error> {
let header = &block.header; let header = &block.header;
let num_uncles = block.uncles.len(); 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. /// Check basic header parameters.
pub fn verify_header_params( pub fn verify_header_params(
header: &Header, header: &Header,
engine: &EthEngine, engine: &dyn EthEngine,
is_full: bool, is_full: bool,
check_seal: bool, check_seal: bool,
) -> Result<(), Error> { ) -> Result<(), Error> {
@ -418,7 +418,7 @@ pub fn verify_header_params(
} }
/// Check header parameters agains parent header. /// 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!( assert!(
header.parent_hash().is_zero() || &parent.hash() == header.parent_hash(), header.parent_hash().is_zero() || &parent.hash() == header.parent_hash(),
"Parent hash should already have been verified; qed" "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())?; let unverified = Unverified::from_rlp(bytes.to_vec())?;
verify_block_basic(&unverified, engine, true) verify_block_basic(&unverified, engine, true)
} }
fn family_test<BC>(bytes: &[u8], engine: &EthEngine, bc: &BC) -> Result<(), Error> fn family_test<BC>(bytes: &[u8], engine: &dyn EthEngine, bc: &BC) -> Result<(), Error>
where where
BC: BlockProvider, BC: BlockProvider,
{ {
@ -697,13 +697,13 @@ mod tests {
let full_params = FullFamilyParams { let full_params = FullFamilyParams {
block: &block, block: &block,
block_provider: bc as &BlockProvider, block_provider: bc as &dyn BlockProvider,
client: &client, client: &client,
}; };
verify_block_family(&block.header, &parent, engine, Some(full_params)) 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())?; let un = Unverified::from_rlp(bytes.to_vec())?;
verify_block_unordered(un, engine, false)?; verify_block_unordered(un, engine, false)?;
Ok(()) Ok(())

View File

@ -33,12 +33,12 @@ where
&self, &self,
header: &Header, header: &Header,
parent: &Header, parent: &Header,
engine: &EthEngine, engine: &dyn EthEngine,
do_full: Option<verification::FullFamilyParams<C>>, do_full: Option<verification::FullFamilyParams<C>>,
) -> Result<(), Error>; ) -> Result<(), Error>;
/// Do a final verification check for an enacted header vs its expected counterpart. /// Do a final verification check for an enacted header vs its expected counterpart.
fn verify_block_final(&self, expected: &Header, got: &Header) -> Result<(), Error>; fn verify_block_final(&self, expected: &Header, got: &Header) -> Result<(), Error>;
/// Verify a block, inspecing external state. /// 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>;
} }

View File

@ -218,7 +218,7 @@ impl From<light_net::Status> for PipProtocolInfo {
/// Only works when IPC is disabled. /// Only works when IPC is disabled.
pub struct AttachedProtocol { pub struct AttachedProtocol {
/// The protocol handler in question. /// The protocol handler in question.
pub handler: Arc<NetworkProtocolHandler + Send + Sync>, pub handler: Arc<dyn NetworkProtocolHandler + Send + Sync>,
/// 3-character ID for the protocol. /// 3-character ID for the protocol.
pub protocol_id: ProtocolId, pub protocol_id: ProtocolId,
/// Supported versions and their packet counts. /// Supported versions and their packet counts.
@ -273,13 +273,13 @@ pub struct Params {
/// Configuration. /// Configuration.
pub config: SyncConfig, pub config: SyncConfig,
/// Blockchain client. /// Blockchain client.
pub chain: Arc<BlockChainClient>, pub chain: Arc<dyn BlockChainClient>,
/// Snapshot service. /// Snapshot service.
pub snapshot_service: Arc<SnapshotService>, pub snapshot_service: Arc<dyn SnapshotService>,
/// Private tx service. /// Private tx service.
pub private_tx_handler: Option<Arc<PrivateTxHandler>>, pub private_tx_handler: Option<Arc<dyn PrivateTxHandler>>,
/// Light data provider. /// Light data provider.
pub provider: Arc<::light::Provider>, pub provider: Arc<dyn crate::light::Provider>,
/// Network layer configuration. /// Network layer configuration.
pub network_config: NetworkConfiguration, pub network_config: NetworkConfiguration,
/// Other protocols to attach. /// Other protocols to attach.
@ -308,7 +308,7 @@ fn light_params(
network_id: u64, network_id: u64,
median_peers: f64, median_peers: f64,
pruning_info: PruningInfo, pruning_info: PruningInfo,
sample_store: Option<Box<SampleStore>>, sample_store: Option<Box<dyn SampleStore>>,
) -> LightParams { ) -> LightParams {
let mut light_params = LightParams { let mut light_params = LightParams {
network_id: network_id, network_id: network_id,
@ -330,7 +330,7 @@ impl EthSync {
/// Creates and register protocol with the network service /// Creates and register protocol with the network service
pub fn new( pub fn new(
params: Params, params: Params,
connection_filter: Option<Arc<ConnectionFilter>>, connection_filter: Option<Arc<dyn ConnectionFilter>>,
) -> Result<Arc<EthSync>, Error> { ) -> Result<Arc<EthSync>, Error> {
let pruning_info = params.chain.pruning_info(); let pruning_info = params.chain.pruning_info();
let light_proto = match params.config.serve_light { 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 { struct SyncProtocolHandler {
/// Shared blockchain client. /// Shared blockchain client.
chain: Arc<BlockChainClient>, chain: Arc<dyn BlockChainClient>,
/// Shared snapshot service. /// Shared snapshot service.
snapshot_service: Arc<SnapshotService>, snapshot_service: Arc<dyn SnapshotService>,
/// Sync strategy /// Sync strategy
sync: ChainSyncApi, sync: ChainSyncApi,
/// Chain overlay used to cache data such as fork block. /// Chain overlay used to cache data such as fork block.
@ -474,7 +474,7 @@ struct SyncProtocolHandler {
} }
impl NetworkProtocolHandler for SyncProtocolHandler { impl NetworkProtocolHandler for SyncProtocolHandler {
fn initialize(&self, io: &NetworkContext) { fn initialize(&self, io: &dyn NetworkContext) {
if io.subprotocol_name() != WARP_SYNC_PROTOCOL_ID { if io.subprotocol_name() != WARP_SYNC_PROTOCOL_ID {
io.register_timer(PEERS_TIMER, Duration::from_millis(700)) io.register_timer(PEERS_TIMER, Duration::from_millis(700))
.expect("Error registering peers timer"); .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( self.sync.dispatch_packet(
&mut NetSyncIo::new(io, &*self.chain, &*self.snapshot_service, &self.overlay), &mut NetSyncIo::new(io, &*self.chain, &*self.snapshot_service, &self.overlay),
*peer, *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"); trace_time!("sync::connected");
// If warp protocol is supported only allow warp handshake // If warp protocol is supported only allow warp handshake
let warp_protocol = io 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"); trace_time!("sync::disconnected");
if io.subprotocol_name() != WARP_SYNC_PROTOCOL_ID { if io.subprotocol_name() != WARP_SYNC_PROTOCOL_ID {
self.sync.write().on_peer_aborting( 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"); trace_time!("sync::timeout");
let mut io = NetSyncIo::new(io, &*self.chain, &*self.snapshot_service, &self.overlay); let mut io = NetSyncIo::new(io, &*self.chain, &*self.snapshot_service, &self.overlay);
match timer { match timer {
@ -697,12 +697,12 @@ impl ChainNotify for EthSync {
/// PIP event handler. /// PIP event handler.
/// Simply queues transactions from light client peers. /// Simply queues transactions from light client peers.
struct TxRelay(Arc<BlockChainClient>); struct TxRelay(Arc<dyn BlockChainClient>);
impl LightHandler for TxRelay { impl LightHandler for TxRelay {
fn on_transactions( fn on_transactions(
&self, &self,
ctx: &EventContext, ctx: &dyn EventContext,
relay: &[::types::transaction::UnverifiedTransaction], relay: &[::types::transaction::UnverifiedTransaction],
) { ) {
trace!(target: "pip", "Relaying {} transactions from peer {}", relay.len(), ctx.peer()); 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. /// Returns the minimum and maximum peers.
fn num_peers_range(&self) -> RangeInclusive<u32>; fn num_peers_range(&self) -> RangeInclusive<u32>;
/// Get network context for protocol. /// 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 { impl ManageNetwork for EthSync {
@ -782,7 +782,7 @@ impl ManageNetwork for EthSync {
self.network.num_peers_range() 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); self.network.with_context_eval(proto, f);
} }
} }
@ -964,7 +964,7 @@ pub trait LightNetworkDispatcher {
/// Execute a closure with a protocol context. /// Execute a closure with a protocol context.
fn with_context<F, T>(&self, f: F) -> Option<T> fn with_context<F, T>(&self, f: F) -> Option<T>
where where
F: FnOnce(&::light::net::BasicContext) -> T; F: FnOnce(&dyn crate::light::net::BasicContext) -> T;
} }
/// Configuration for the light sync. /// Configuration for the light sync.
@ -978,7 +978,7 @@ pub struct LightSyncParams<L> {
/// Subprotocol name. /// Subprotocol name.
pub subprotocol_name: [u8; 3], pub subprotocol_name: [u8; 3],
/// Other handlers to attach. /// Other handlers to attach.
pub handlers: Vec<Arc<LightHandler>>, pub handlers: Vec<Arc<dyn LightHandler>>,
/// Other subprotocols to run. /// Other subprotocols to run.
pub attached_protos: Vec<AttachedProtocol>, pub attached_protos: Vec<AttachedProtocol>,
} }
@ -986,7 +986,7 @@ pub struct LightSyncParams<L> {
/// Service for light synchronization. /// Service for light synchronization.
pub struct LightSync { pub struct LightSync {
proto: Arc<LightProtocol>, proto: Arc<LightProtocol>,
sync: Arc<SyncInfo + Sync + Send>, sync: Arc<dyn SyncInfo + Sync + Send>,
attached_protos: Vec<AttachedProtocol>, attached_protos: Vec<AttachedProtocol>,
network: NetworkService, network: NetworkService,
subprotocol_name: [u8; 3], subprotocol_name: [u8; 3],
@ -1040,7 +1040,7 @@ impl LightSync {
} }
impl ::std::ops::Deref for LightSync { impl ::std::ops::Deref for LightSync {
type Target = ::light_sync::SyncInfo; type Target = dyn crate::light_sync::SyncInfo;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&*self.sync &*self.sync
@ -1050,7 +1050,7 @@ impl ::std::ops::Deref for LightSync {
impl LightNetworkDispatcher for LightSync { impl LightNetworkDispatcher for LightSync {
fn with_context<F, T>(&self, f: F) -> Option<T> fn with_context<F, T>(&self, f: F) -> Option<T>
where where
F: FnOnce(&::light::net::BasicContext) -> T, F: FnOnce(&dyn crate::light::net::BasicContext) -> T,
{ {
self.network self.network
.with_context_eval(self.subprotocol_name, move |ctx| { .with_context_eval(self.subprotocol_name, move |ctx| {
@ -1119,7 +1119,7 @@ impl ManageNetwork for LightSync {
self.network.num_peers_range() 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); self.network.with_context_eval(proto, f);
} }
} }

View File

@ -231,7 +231,7 @@ impl BlockDownloader {
/// Add new block headers. /// Add new block headers.
pub fn import_headers( pub fn import_headers(
&mut self, &mut self,
io: &mut SyncIo, io: &mut dyn SyncIo,
r: &Rlp, r: &Rlp,
expected_hash: H256, expected_hash: H256,
) -> Result<DownloadAction, BlockDownloaderImportError> { ) -> Result<DownloadAction, BlockDownloaderImportError> {
@ -463,7 +463,7 @@ impl BlockDownloader {
Ok(()) Ok(())
} }
fn start_sync_round(&mut self, io: &mut SyncIo) { fn start_sync_round(&mut self, io: &mut dyn SyncIo) {
self.state = State::ChainHead; self.state = State::ChainHead;
trace_sync!( trace_sync!(
self, self,
@ -541,7 +541,7 @@ impl BlockDownloader {
pub fn request_blocks( pub fn request_blocks(
&mut self, &mut self,
peer_id: PeerId, peer_id: PeerId,
io: &mut SyncIo, io: &mut dyn SyncIo,
num_active_peers: usize, num_active_peers: usize,
) -> Option<BlockRequest> { ) -> Option<BlockRequest> {
match self.state { 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. /// 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 /// 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 download_action = DownloadAction::None;
let mut imported = HashSet::new(); let mut imported = HashSet::new();
let blocks = self.blocks.drain(); let blocks = self.blocks.drain();
@ -748,7 +752,7 @@ mod tests {
fn import_headers( fn import_headers(
headers: &[BlockHeader], headers: &[BlockHeader],
downloader: &mut BlockDownloader, downloader: &mut BlockDownloader,
io: &mut SyncIo, io: &mut dyn SyncIo,
) -> Result<DownloadAction, BlockDownloaderImportError> { ) -> Result<DownloadAction, BlockDownloaderImportError> {
let mut stream = RlpStream::new(); let mut stream = RlpStream::new();
stream.append_list(headers); stream.append_list(headers);
@ -761,7 +765,7 @@ mod tests {
fn import_headers_ok( fn import_headers_ok(
headers: &[BlockHeader], headers: &[BlockHeader],
downloader: &mut BlockDownloader, downloader: &mut BlockDownloader,
io: &mut SyncIo, io: &mut dyn SyncIo,
) { ) {
let res = import_headers(headers, downloader, io); let res = import_headers(headers, downloader, io);
assert!(res.is_ok()); assert!(res.is_ok());

View File

@ -619,7 +619,7 @@ mod test {
client.add_blocks(100, EachBlockWith::Nothing); client.add_blocks(100, EachBlockWith::Nothing);
let hashes = (0..100) let hashes = (0..100)
.map(|i| { .map(|i| {
(&client as &BlockChainClient) (&client as &dyn BlockChainClient)
.block_hash(BlockId::Number(i)) .block_hash(BlockId::Number(i))
.unwrap() .unwrap()
}) })
@ -639,7 +639,7 @@ mod test {
client.add_blocks(nblocks, EachBlockWith::Nothing); client.add_blocks(nblocks, EachBlockWith::Nothing);
let blocks: Vec<_> = (0..nblocks) let blocks: Vec<_> = (0..nblocks)
.map(|i| { .map(|i| {
(&client as &BlockChainClient) (&client as &dyn BlockChainClient)
.block(BlockId::Number(i as BlockNumber)) .block(BlockId::Number(i as BlockNumber))
.unwrap() .unwrap()
.into_inner() .into_inner()
@ -719,7 +719,7 @@ mod test {
client.add_blocks(nblocks, EachBlockWith::Nothing); client.add_blocks(nblocks, EachBlockWith::Nothing);
let blocks: Vec<_> = (0..nblocks) let blocks: Vec<_> = (0..nblocks)
.map(|i| { .map(|i| {
(&client as &BlockChainClient) (&client as &dyn BlockChainClient)
.block(BlockId::Number(i as BlockNumber)) .block(BlockId::Number(i as BlockNumber))
.unwrap() .unwrap()
.into_inner() .into_inner()
@ -755,7 +755,7 @@ mod test {
client.add_blocks(nblocks, EachBlockWith::Nothing); client.add_blocks(nblocks, EachBlockWith::Nothing);
let blocks: Vec<_> = (0..nblocks) let blocks: Vec<_> = (0..nblocks)
.map(|i| { .map(|i| {
(&client as &BlockChainClient) (&client as &dyn BlockChainClient)
.block(BlockId::Number(i as BlockNumber)) .block(BlockId::Number(i as BlockNumber))
.unwrap() .unwrap()
.into_inner() .into_inner()

View File

@ -54,7 +54,7 @@ impl SyncHandler {
/// Handle incoming packet from peer /// Handle incoming packet from peer
pub fn on_packet( pub fn on_packet(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer: PeerId, peer: PeerId,
packet_id: u8, packet_id: u8,
data: &[u8], data: &[u8],
@ -102,13 +102,13 @@ impl SyncHandler {
} }
/// Called when peer sends us new consensus packet /// 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); trace!(target: "sync", "Received consensus packet from {:?}", peer_id);
io.chain().queue_consensus_message(r.as_raw().to_vec()); io.chain().queue_consensus_message(r.as_raw().to_vec());
} }
/// Called by peer when it is disconnecting /// 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)); trace!(target: "sync", "== Disconnecting {}: {}", peer_id, io.peer_version(peer_id));
sync.handshaking_peers.remove(&peer_id); sync.handshaking_peers.remove(&peer_id);
if sync.peers.contains_key(&peer_id) { if sync.peers.contains_key(&peer_id) {
@ -139,7 +139,7 @@ impl SyncHandler {
} }
/// Called when a new peer is connected /// 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)); trace!(target: "sync", "== Connected {}: {}", peer, io.peer_version(peer));
if let Err(e) = sync.send_status(io, peer) { if let Err(e) = sync.send_status(io, peer) {
debug!(target:"sync", "Error sending status request: {:?}", e); debug!(target:"sync", "Error sending status request: {:?}", e);
@ -152,7 +152,7 @@ impl SyncHandler {
/// Called by peer once it has new block bodies /// Called by peer once it has new block bodies
pub fn on_peer_new_block( pub fn on_peer_new_block(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
r: &Rlp, r: &Rlp,
) -> Result<(), DownloaderImportError> { ) -> Result<(), DownloaderImportError> {
@ -221,7 +221,7 @@ impl SyncHandler {
/// Handles `NewHashes` packet. Initiates headers download for any unknown hashes. /// Handles `NewHashes` packet. Initiates headers download for any unknown hashes.
pub fn on_peer_new_hashes( pub fn on_peer_new_hashes(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
r: &Rlp, r: &Rlp,
) -> Result<(), DownloaderImportError> { ) -> Result<(), DownloaderImportError> {
@ -305,7 +305,7 @@ impl SyncHandler {
/// Called by peer once it has new block bodies /// Called by peer once it has new block bodies
fn on_peer_block_bodies( fn on_peer_block_bodies(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
r: &Rlp, r: &Rlp,
) -> Result<(), DownloaderImportError> { ) -> Result<(), DownloaderImportError> {
@ -360,7 +360,7 @@ impl SyncHandler {
fn on_peer_fork_header( fn on_peer_fork_header(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
r: &Rlp, r: &Rlp,
) -> Result<(), DownloaderImportError> { ) -> Result<(), DownloaderImportError> {
@ -404,7 +404,7 @@ impl SyncHandler {
/// Called by peer once it has new block headers during sync /// Called by peer once it has new block headers during sync
fn on_peer_block_headers( fn on_peer_block_headers(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
r: &Rlp, r: &Rlp,
) -> Result<(), DownloaderImportError> { ) -> Result<(), DownloaderImportError> {
@ -484,7 +484,7 @@ impl SyncHandler {
/// Called by peer once it has new block receipts /// Called by peer once it has new block receipts
fn on_peer_block_receipts( fn on_peer_block_receipts(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
r: &Rlp, r: &Rlp,
) -> Result<(), DownloaderImportError> { ) -> Result<(), DownloaderImportError> {
@ -539,7 +539,7 @@ impl SyncHandler {
/// Called when snapshot manifest is downloaded from a peer. /// Called when snapshot manifest is downloaded from a peer.
fn on_snapshot_manifest( fn on_snapshot_manifest(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
r: &Rlp, r: &Rlp,
) -> Result<(), DownloaderImportError> { ) -> Result<(), DownloaderImportError> {
@ -580,7 +580,7 @@ impl SyncHandler {
/// Called when snapshot data is downloaded from a peer. /// Called when snapshot data is downloaded from a peer.
fn on_snapshot_data( fn on_snapshot_data(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
r: &Rlp, r: &Rlp,
) -> Result<(), DownloaderImportError> { ) -> Result<(), DownloaderImportError> {
@ -653,7 +653,7 @@ impl SyncHandler {
/// Called by peer to report status /// Called by peer to report status
fn on_peer_status( fn on_peer_status(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
r: &Rlp, r: &Rlp,
) -> Result<(), DownloaderImportError> { ) -> Result<(), DownloaderImportError> {
@ -768,7 +768,7 @@ impl SyncHandler {
/// Called when peer sends us new transactions /// Called when peer sends us new transactions
pub fn on_peer_transactions( pub fn on_peer_transactions(
sync: &ChainSync, sync: &ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
r: &Rlp, r: &Rlp,
) -> Result<(), PacketDecodeError> { ) -> Result<(), PacketDecodeError> {
@ -799,7 +799,7 @@ impl SyncHandler {
/// Called when peer sends us signed private transaction packet /// Called when peer sends us signed private transaction packet
fn on_signed_private_transaction( fn on_signed_private_transaction(
sync: &mut ChainSync, sync: &mut ChainSync,
_io: &mut SyncIo, _io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
r: &Rlp, r: &Rlp,
) -> Result<(), DownloaderImportError> { ) -> Result<(), DownloaderImportError> {
@ -832,7 +832,7 @@ impl SyncHandler {
/// Called when peer sends us new private transaction packet /// Called when peer sends us new private transaction packet
fn on_private_transaction( fn on_private_transaction(
sync: &mut ChainSync, sync: &mut ChainSync,
_io: &mut SyncIo, _io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
r: &Rlp, r: &Rlp,
) -> Result<(), DownloaderImportError> { ) -> Result<(), DownloaderImportError> {

View File

@ -392,8 +392,8 @@ impl ChainSyncApi {
/// Creates new `ChainSyncApi` /// Creates new `ChainSyncApi`
pub fn new( pub fn new(
config: SyncConfig, config: SyncConfig,
chain: &BlockChainClient, chain: &dyn BlockChainClient,
private_tx_handler: Option<Arc<PrivateTxHandler>>, private_tx_handler: Option<Arc<dyn PrivateTxHandler>>,
priority_tasks: mpsc::Receiver<PriorityTask>, priority_tasks: mpsc::Receiver<PriorityTask>,
) -> Self { ) -> Self {
ChainSyncApi { ChainSyncApi {
@ -429,7 +429,7 @@ impl ChainSyncApi {
} }
/// Dispatch incoming requests and responses /// 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) 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 /// NOTE This method should only handle stuff that can be canceled and would reach other peers
/// by other means. /// 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<Duration> { fn check_deadline(deadline: Instant) -> Option<Duration> {
let now = Instant::now(); let now = Instant::now();
if now > deadline { if now > deadline {
@ -516,7 +516,11 @@ impl ChainSyncApi {
// Static methods // Static methods
impl ChainSync { impl ChainSync {
/// creates rlp to send for the tree defined by 'from' and 'to' hashes /// 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<Bytes> { fn create_new_hashes_rlp(
chain: &dyn BlockChainClient,
from: &H256,
to: &H256,
) -> Option<Bytes> {
match chain.tree_route(from, to) { match chain.tree_route(from, to) {
Some(route) => { Some(route) => {
let uncles = chain.find_uncles(from).unwrap_or_else(Vec::new); 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 /// 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( Self::create_block_rlp(
&chain &chain
.block(BlockId::Hash(chain.chain_info().best_block_hash)) .block(BlockId::Hash(chain.chain_info().best_block_hash))
@ -562,7 +566,7 @@ impl ChainSync {
} }
/// creates given hash block rlp for the given client /// 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( Self::create_block_rlp(
&chain &chain
.block(BlockId::Hash(hash.clone())) .block(BlockId::Hash(hash.clone()))
@ -585,7 +589,7 @@ impl ChainSync {
peers 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; let best_block = chain.chain_info().best_block_number;
match warp_sync { match warp_sync {
WarpSync::Enabled => SyncState::WaitingPeers, WarpSync::Enabled => SyncState::WaitingPeers,
@ -638,7 +642,7 @@ pub struct ChainSync {
/// Enable ancient block downloading /// Enable ancient block downloading
download_old_blocks: bool, download_old_blocks: bool,
/// Shared private tx service. /// Shared private tx service.
private_tx_handler: Option<Arc<PrivateTxHandler>>, private_tx_handler: Option<Arc<dyn PrivateTxHandler>>,
/// Enable warp sync. /// Enable warp sync.
warp_sync: WarpSync, warp_sync: WarpSync,
} }
@ -647,8 +651,8 @@ impl ChainSync {
/// Create a new instance of syncing strategy. /// Create a new instance of syncing strategy.
pub fn new( pub fn new(
config: SyncConfig, config: SyncConfig,
chain: &BlockChainClient, chain: &dyn BlockChainClient,
private_tx_handler: Option<Arc<PrivateTxHandler>>, private_tx_handler: Option<Arc<dyn PrivateTxHandler>>,
) -> Self { ) -> Self {
let chain_info = chain.chain_info(); let chain_info = chain.chain_info();
let best_block = chain.chain_info().best_block_number; let best_block = chain.chain_info().best_block_number;
@ -744,14 +748,14 @@ impl ChainSync {
} }
/// Abort all sync activity /// 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.reset_and_continue(io);
self.peers.clear(); self.peers.clear();
} }
/// Reset sync. Clear all downloaded data but keep the queue. /// 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. /// 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<SyncState>) { fn reset(&mut self, io: &mut dyn SyncIo, state: Option<SyncState>) {
self.new_blocks.reset(); self.new_blocks.reset();
let chain_info = io.chain().chain_info(); let chain_info = io.chain().chain_info();
for (_, ref mut p) in &mut self.peers { for (_, ref mut p) in &mut self.peers {
@ -770,7 +774,7 @@ impl ChainSync {
} }
/// Restart sync /// 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"); trace!(target: "sync", "Restarting");
if self.state == SyncState::SnapshotData { if self.state == SyncState::SnapshotData {
debug!(target:"sync", "Aborting snapshot restore"); 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 /// Remove peer from active peer set. Peer will be reactivated on the next sync
/// round. /// 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); trace!(target: "sync", "Deactivating peer {}", peer_id);
self.active_peers.remove(&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() { if !self.warp_sync.is_enabled() || io.snapshot_service().supported_versions().is_none() {
trace!(target: "sync", "Skipping warp sync. Disabled or not supported."); trace!(target: "sync", "Skipping warp sync. Disabled or not supported.");
return; 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() { if !self.snapshot.have_manifest() {
for p in peers { for p in peers {
if self 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 /// 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.update_targets(io.chain());
self.reset_and_continue(io); self.reset_and_continue(io);
} }
/// Update sync after the blockchain has been changed externally. /// 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 // Do not assume that the block queue/chain still has our last_imported_block
let chain = chain.chain_info(); let chain = chain.chain_info();
self.new_blocks = BlockDownloader::new( self.new_blocks = BlockDownloader::new(
@ -923,7 +927,7 @@ impl ChainSync {
} }
/// Resume downloading /// 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 { if self.state == SyncState::Waiting {
trace!(target: "sync", "Waiting for the block queue"); trace!(target: "sync", "Waiting for the block queue");
} else if self.state == SyncState::SnapshotWaiting { } else if self.state == SyncState::SnapshotWaiting {
@ -974,7 +978,7 @@ impl ChainSync {
} }
/// Called after all blocks have been downloaded /// 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"); trace!(target: "sync", "Sync complete");
self.reset(io, Some(SyncState::Idle)); 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. /// 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) { if !self.active_peers.contains(&peer_id) {
trace!(target: "sync", "Skipping deactivated peer {}", peer_id); trace!(target: "sync", "Skipping deactivated peer {}", peer_id);
return; 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. /// 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 { match block_set {
BlockSet::NewBlocks => { BlockSet::NewBlocks => {
if self if self
@ -1201,7 +1205,7 @@ impl ChainSync {
} }
/// Send Status message /// 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_version = io.protocol_version(&WARP_SYNC_PROTOCOL_ID, peer);
let warp_protocol = warp_protocol_version != 0; let warp_protocol = warp_protocol_version != 0;
let private_tx_protocol = warp_protocol_version >= PAR_PROTOCOL_VERSION_3.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()) 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 tick = Instant::now();
let mut aborting = Vec::new(); let mut aborting = Vec::new();
for (peer_id, peer) in &self.peers { 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 { match self.state {
SyncState::Waiting if !io.chain().queue_info().is_full() => { SyncState::Waiting if !io.chain().queue_info().is_full() => {
self.state = SyncState::Blocks; self.state = SyncState::Blocks;
@ -1369,7 +1373,7 @@ impl ChainSync {
} }
/// Maintain other peers. Send out any new blocks and transactions /// 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.maybe_start_snapshot_sync(io);
self.check_resume(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 /// called when block is imported to chain - propagates the blocks and updates transactions sent to peers
pub fn chain_new_blocks( pub fn chain_new_blocks(
&mut self, &mut self,
io: &mut SyncIo, io: &mut dyn SyncIo,
_imported: &[H256], _imported: &[H256],
invalid: &[H256], invalid: &[H256],
enacted: &[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); SyncHandler::on_packet(self, io, peer, packet_id, data);
} }
/// Called by peer when it is disconnecting /// 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); SyncHandler::on_peer_aborting(self, io, peer);
} }
/// Called when a new peer is connected /// 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); SyncHandler::on_peer_connected(self, io, peer);
} }
/// propagates new transactions to all peers /// 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); let deadline = Instant::now() + Duration::from_millis(500);
SyncPropagator::propagate_new_transactions(self, io, || { SyncPropagator::propagate_new_transactions(self, io, || {
if deadline > Instant::now() { if deadline > Instant::now() {
@ -1437,14 +1441,14 @@ impl ChainSync {
} }
/// Broadcast consensus message to peers. /// 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); SyncPropagator::propagate_consensus_packet(self, io, packet);
} }
/// Broadcast private transaction message to peers. /// Broadcast private transaction message to peers.
pub fn propagate_private_transaction( pub fn propagate_private_transaction(
&mut self, &mut self,
io: &mut SyncIo, io: &mut dyn SyncIo,
transaction_hash: H256, transaction_hash: H256,
packet_id: SyncPacket, packet_id: SyncPacket,
packet: Bytes, packet: Bytes,
@ -1558,7 +1562,10 @@ pub mod tests {
assert!(!sync_status(SyncState::Idle).is_syncing(queue_info(0, 0))); 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); let mut sync = ChainSync::new(SyncConfig::default(), client, None);
insert_dummy_peer(&mut sync, 0, peer_latest_hash); insert_dummy_peer(&mut sync, 0, peer_latest_hash);
sync sync

View File

@ -43,13 +43,13 @@ impl SyncPropagator {
pub fn propagate_blocks( pub fn propagate_blocks(
sync: &mut ChainSync, sync: &mut ChainSync,
chain_info: &BlockChainInfo, chain_info: &BlockChainInfo,
io: &mut SyncIo, io: &mut dyn SyncIo,
blocks: &[H256], blocks: &[H256],
peers: &[PeerId], peers: &[PeerId],
) -> usize { ) -> usize {
trace!(target: "sync", "Sending NewBlocks to {:?}", peers); trace!(target: "sync", "Sending NewBlocks to {:?}", peers);
let sent = peers.len(); 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 { for peer_id in peers {
SyncPropagator::send_packet(io, *peer_id, NewBlockPacket, rlp.clone()); SyncPropagator::send_packet(io, *peer_id, NewBlockPacket, rlp.clone());
@ -76,7 +76,7 @@ impl SyncPropagator {
pub fn propagate_new_hashes( pub fn propagate_new_hashes(
sync: &mut ChainSync, sync: &mut ChainSync,
chain_info: &BlockChainInfo, chain_info: &BlockChainInfo,
io: &mut SyncIo, io: &mut dyn SyncIo,
peers: &[PeerId], peers: &[PeerId],
) -> usize { ) -> usize {
trace!(target: "sync", "Sending NewHashes to {:?}", peers); trace!(target: "sync", "Sending NewHashes to {:?}", peers);
@ -101,7 +101,7 @@ impl SyncPropagator {
/// propagates new transactions to all peers /// propagates new transactions to all peers
pub fn propagate_new_transactions<F: FnMut() -> bool>( pub fn propagate_new_transactions<F: FnMut() -> bool>(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
mut should_continue: F, mut should_continue: F,
) -> usize { ) -> usize {
// Early out if nobody to send to. // Early out if nobody to send to.
@ -159,7 +159,7 @@ impl SyncPropagator {
fn propagate_transactions_to_peers<F: FnMut() -> bool>( fn propagate_transactions_to_peers<F: FnMut() -> bool>(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peers: Vec<PeerId>, peers: Vec<PeerId>,
transactions: Vec<&SignedTransaction>, transactions: Vec<&SignedTransaction>,
mut should_continue: F, mut should_continue: F,
@ -179,7 +179,7 @@ impl SyncPropagator {
// Clear old transactions from stats // Clear old transactions from stats
sync.transactions_stats.retain(&all_transactions_hashes); 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(); let size = rlp.len();
SyncPropagator::send_packet(io, peer_id, TransactionsPacket, rlp); SyncPropagator::send_packet(io, peer_id, TransactionsPacket, rlp);
trace!(target: "sync", "{:02} <- Transactions ({} entries; {} bytes)", peer_id, sent, size); trace!(target: "sync", "{:02} <- Transactions ({} entries; {} bytes)", peer_id, sent, size);
@ -279,7 +279,7 @@ impl SyncPropagator {
sent_to_peers 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(); let chain_info = io.chain().chain_info();
if (((chain_info.best_block_number as i64) - (sync.last_sent_block_number as i64)).abs() if (((chain_info.best_block_number as i64) - (sync.last_sent_block_number as i64)).abs()
as BlockNumber) as BlockNumber)
@ -304,7 +304,11 @@ impl SyncPropagator {
} }
/// Distribute valid proposed blocks to subset of current peers. /// 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(); let peers = sync.get_consensus_peers();
trace!(target: "sync", "Sending proposed blocks to {:?}", peers); trace!(target: "sync", "Sending proposed blocks to {:?}", peers);
for block in proposed { for block in proposed {
@ -316,7 +320,7 @@ impl SyncPropagator {
} }
/// Broadcast consensus message to peers. /// 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()); let lucky_peers = ChainSync::select_random_peers(&sync.get_consensus_peers());
trace!(target: "sync", "Sending consensus packet to {:?}", lucky_peers); trace!(target: "sync", "Sending consensus packet to {:?}", lucky_peers);
for peer_id in lucky_peers { for peer_id in lucky_peers {
@ -327,7 +331,7 @@ impl SyncPropagator {
/// Broadcast private transaction message to peers. /// Broadcast private transaction message to peers.
pub fn propagate_private_transaction( pub fn propagate_private_transaction(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
transaction_hash: H256, transaction_hash: H256,
packet_id: SyncPacket, packet_id: SyncPacket,
packet: Bytes, packet: Bytes,
@ -367,7 +371,12 @@ impl SyncPropagator {
} }
/// Generic packet sender /// 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) { if let Err(e) = sync.send(peer_id, packet_id, packet) {
debug!(target:"sync", "Error sending packet: {:?}", e); debug!(target:"sync", "Error sending packet: {:?}", e);
sync.disconnect_peer(peer_id); sync.disconnect_peer(peer_id);

View File

@ -40,7 +40,7 @@ impl SyncRequester {
/// Perform block download request` /// Perform block download request`
pub fn request_blocks( pub fn request_blocks(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
request: BlockRequest, request: BlockRequest,
block_set: BlockSet, block_set: BlockSet,
@ -63,7 +63,7 @@ impl SyncRequester {
/// Request block bodies from a peer /// Request block bodies from a peer
fn request_bodies( fn request_bodies(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
hashes: Vec<H256>, hashes: Vec<H256>,
set: BlockSet, set: BlockSet,
@ -89,7 +89,7 @@ impl SyncRequester {
/// Request headers from a peer by block number /// Request headers from a peer by block number
pub fn request_fork_header( pub fn request_fork_header(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
n: BlockNumber, n: BlockNumber,
) { ) {
@ -110,7 +110,7 @@ impl SyncRequester {
} }
/// Find some headers or blocks to download for a peer. /// 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 // find chunk data to download
if let Some(hash) = sync.snapshot.needed_chunk() { if let Some(hash) = sync.snapshot.needed_chunk() {
if let Some(ref mut peer) = sync.peers.get_mut(&peer_id) { if let Some(ref mut peer) = sync.peers.get_mut(&peer_id) {
@ -121,7 +121,7 @@ impl SyncRequester {
} }
/// Request snapshot manifest from a peer. /// 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); trace!(target: "sync", "{} <- GetSnapshotManifest", peer_id);
let rlp = RlpStream::new_list(0); let rlp = RlpStream::new_list(0);
SyncRequester::send_request( SyncRequester::send_request(
@ -137,7 +137,7 @@ impl SyncRequester {
/// Request headers from a peer by block hash /// Request headers from a peer by block hash
fn request_headers_by_hash( fn request_headers_by_hash(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
h: &H256, h: &H256,
count: u64, count: u64,
@ -167,7 +167,7 @@ impl SyncRequester {
/// Request block receipts from a peer /// Request block receipts from a peer
fn request_receipts( fn request_receipts(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
hashes: Vec<H256>, hashes: Vec<H256>,
set: BlockSet, set: BlockSet,
@ -193,7 +193,7 @@ impl SyncRequester {
/// Request snapshot chunk from a peer. /// Request snapshot chunk from a peer.
fn request_snapshot_chunk( fn request_snapshot_chunk(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
chunk: &H256, chunk: &H256,
) { ) {
@ -213,7 +213,7 @@ impl SyncRequester {
/// Generic request sender /// Generic request sender
fn send_request( fn send_request(
sync: &mut ChainSync, sync: &mut ChainSync,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer_id: PeerId, peer_id: PeerId,
asking: PeerAsking, asking: PeerAsking,
packet_id: SyncPacket, packet_id: SyncPacket,

View File

@ -49,7 +49,7 @@ impl SyncSupplier {
// to chain sync from the outside world. // to chain sync from the outside world.
pub fn dispatch_packet( pub fn dispatch_packet(
sync: &RwLock<ChainSync>, sync: &RwLock<ChainSync>,
io: &mut SyncIo, io: &mut dyn SyncIo,
peer: PeerId, peer: PeerId,
packet_id: u8, packet_id: u8,
data: &[u8], data: &[u8],
@ -143,7 +143,7 @@ impl SyncSupplier {
} }
/// Respond to GetBlockHeaders request /// 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(); let payload_soft_limit = io.payload_soft_limit();
// Packet layout: // Packet layout:
// [ block: { P , B_32 }, maxHeaders: P, skip: P, reverse: P in { 0 , 1 } ] // [ block: { P , B_32 }, maxHeaders: P, skip: P, reverse: P in { 0 , 1 } ]
@ -226,7 +226,7 @@ impl SyncSupplier {
} }
/// Respond to GetBlockBodies request /// 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 payload_soft_limit = io.payload_soft_limit();
let mut count = r.item_count().unwrap_or(0); let mut count = r.item_count().unwrap_or(0);
if count == 0 { if count == 0 {
@ -253,7 +253,7 @@ impl SyncSupplier {
} }
/// Respond to GetNodeData request /// 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 payload_soft_limit = io.payload_soft_limit();
let mut count = r.item_count().unwrap_or(0); let mut count = r.item_count().unwrap_or(0);
trace!(target: "sync", "{} -> GetNodeData: {} entries", peer_id, count); trace!(target: "sync", "{} -> GetNodeData: {} entries", peer_id, count);
@ -284,7 +284,7 @@ impl SyncSupplier {
Ok(Some((NodeDataPacket.id(), rlp))) 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 payload_soft_limit = io.payload_soft_limit();
let mut count = rlp.item_count().unwrap_or(0); let mut count = rlp.item_count().unwrap_or(0);
trace!(target: "sync", "{} -> GetReceipts: {} entries", peer_id, count); trace!(target: "sync", "{} -> GetReceipts: {} entries", peer_id, count);
@ -313,7 +313,7 @@ impl SyncSupplier {
} }
/// Respond to GetSnapshotManifest request /// 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); let count = r.item_count().unwrap_or(0);
trace!(target: "warp", "{} -> GetSnapshotManifest", peer_id); trace!(target: "warp", "{} -> GetSnapshotManifest", peer_id);
if count != 0 { if count != 0 {
@ -336,7 +336,7 @@ impl SyncSupplier {
} }
/// Respond to GetSnapshotData request /// 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)?; let hash: H256 = r.val_at(0)?;
trace!(target: "warp", "{} -> GetSnapshotData {:?}", peer_id, hash); trace!(target: "warp", "{} -> GetSnapshotData {:?}", peer_id, hash);
let rlp = match io.snapshot_service().chunk(hash) { let rlp = match io.snapshot_service().chunk(hash) {
@ -355,14 +355,14 @@ impl SyncSupplier {
} }
fn return_rlp<FRlp, FError>( fn return_rlp<FRlp, FError>(
io: &mut SyncIo, io: &mut dyn SyncIo,
rlp: &Rlp, rlp: &Rlp,
peer: PeerId, peer: PeerId,
rlp_func: FRlp, rlp_func: FRlp,
error_func: FError, error_func: FError,
) -> Result<(), PacketDecodeError> ) -> Result<(), PacketDecodeError>
where where
FRlp: Fn(&SyncIo, &Rlp, PeerId) -> RlpResponseResult, FRlp: Fn(&dyn SyncIo, &Rlp, PeerId) -> RlpResponseResult,
FError: FnOnce(network::Error) -> String, FError: FnOnce(network::Error) -> String,
{ {
let response = rlp_func(io, rlp, peer); let response = rlp_func(io, rlp, peer);
@ -420,7 +420,7 @@ mod test {
client.add_blocks(100, EachBlockWith::Nothing); client.add_blocks(100, EachBlockWith::Nothing);
let blocks: Vec<_> = (0..100) let blocks: Vec<_> = (0..100)
.map(|i| { .map(|i| {
(&client as &BlockChainClient) (&client as &dyn BlockChainClient)
.block(BlockId::Number(i as BlockNumber)) .block(BlockId::Number(i as BlockNumber))
.map(|b| b.into_inner()) .map(|b| b.into_inner())
.unwrap() .unwrap()

View File

@ -118,7 +118,7 @@ impl AncestorSearch {
} }
} }
fn process_response<L>(self, ctx: &ResponseContext, client: &L) -> AncestorSearch fn process_response<L>(self, ctx: &dyn ResponseContext, client: &L) -> AncestorSearch
where where
L: AsLightClient, L: AsLightClient,
{ {
@ -261,7 +261,7 @@ impl Deref for SyncStateWrapper {
struct ResponseCtx<'a> { struct ResponseCtx<'a> {
peer: PeerId, peer: PeerId,
req_id: ReqId, req_id: ReqId,
ctx: &'a BasicContext, ctx: &'a dyn BasicContext,
data: &'a [encoded::Header], data: &'a [encoded::Header],
} }
@ -302,7 +302,7 @@ struct PendingReq {
impl<L: AsLightClient + Send + Sync> Handler for LightSync<L> { impl<L: AsLightClient + Send + Sync> Handler for LightSync<L> {
fn on_connect( fn on_connect(
&self, &self,
ctx: &EventContext, ctx: &dyn EventContext,
status: &Status, status: &Status,
capabilities: &Capabilities, capabilities: &Capabilities,
) -> PeerStatus { ) -> PeerStatus {
@ -331,7 +331,7 @@ impl<L: AsLightClient + Send + Sync> Handler for LightSync<L> {
} }
} }
fn on_disconnect(&self, ctx: &EventContext, unfulfilled: &[ReqId]) { fn on_disconnect(&self, ctx: &dyn EventContext, unfulfilled: &[ReqId]) {
let peer_id = ctx.peer(); let peer_id = ctx.peer();
let peer = match self.peers.write().remove(&peer_id).map(|p| p.into_inner()) { let peer = match self.peers.write().remove(&peer_id).map(|p| p.into_inner()) {
@ -389,7 +389,7 @@ impl<L: AsLightClient + Send + Sync> Handler for LightSync<L> {
self.maintain_sync(ctx.as_basic()); 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 (last_td, chain_info) = {
let peers = self.peers.read(); let peers = self.peers.read();
match peers.get(&ctx.peer()) { match peers.get(&ctx.peer()) {
@ -425,7 +425,7 @@ impl<L: AsLightClient + Send + Sync> Handler for LightSync<L> {
self.maintain_sync(ctx.as_basic()); 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(); let peer = ctx.peer();
if !self.peers.read().contains_key(&peer) { if !self.peers.read().contains_key(&peer) {
return; return;
@ -469,7 +469,7 @@ impl<L: AsLightClient + Send + Sync> Handler for LightSync<L> {
self.maintain_sync(ctx.as_basic()); self.maintain_sync(ctx.as_basic());
} }
fn tick(&self, ctx: &BasicContext) { fn tick(&self, ctx: &dyn BasicContext) {
self.maintain_sync(ctx); self.maintain_sync(ctx);
} }
} }
@ -502,7 +502,7 @@ impl<L: AsLightClient> LightSync<L> {
} }
// handles request dispatch, block import, state machine transitions, and timeouts. // 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::{ use ethcore::error::{
Error as EthcoreError, ErrorKind as EthcoreErrorKind, ImportErrorKind, Error as EthcoreError, ErrorKind as EthcoreErrorKind, ImportErrorKind,
}; };

View File

@ -51,7 +51,7 @@ impl Snapshot {
} }
/// Sync the Snapshot completed chunks with the Snapshot Service /// 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 { if self.initialized {
return; return;
} }

View File

@ -37,9 +37,9 @@ pub trait SyncIo {
/// Send a packet to a peer using specified protocol. /// Send a packet to a peer using specified protocol.
fn send(&mut self, peer_id: PeerId, packet_id: SyncPacket, data: Vec<u8>) -> Result<(), Error>; fn send(&mut self, peer_id: PeerId, packet_id: SyncPacket, data: Vec<u8>) -> Result<(), Error>;
/// Get the blockchain /// Get the blockchain
fn chain(&self) -> &BlockChainClient; fn chain(&self) -> &dyn BlockChainClient;
/// Get the snapshot service. /// Get the snapshot service.
fn snapshot_service(&self) -> &SnapshotService; fn snapshot_service(&self) -> &dyn SnapshotService;
/// Returns peer version identifier /// Returns peer version identifier
fn peer_version(&self, peer_id: PeerId) -> ClientVersion { fn peer_version(&self, peer_id: PeerId) -> ClientVersion {
ClientVersion::from(peer_id.to_string()) ClientVersion::from(peer_id.to_string())
@ -64,18 +64,18 @@ pub trait SyncIo {
/// Wraps `NetworkContext` and the blockchain client /// Wraps `NetworkContext` and the blockchain client
pub struct NetSyncIo<'s> { pub struct NetSyncIo<'s> {
network: &'s NetworkContext, network: &'s dyn NetworkContext,
chain: &'s BlockChainClient, chain: &'s dyn BlockChainClient,
snapshot_service: &'s SnapshotService, snapshot_service: &'s dyn SnapshotService,
chain_overlay: &'s RwLock<HashMap<BlockNumber, Bytes>>, chain_overlay: &'s RwLock<HashMap<BlockNumber, Bytes>>,
} }
impl<'s> NetSyncIo<'s> { impl<'s> NetSyncIo<'s> {
/// Creates a new instance from the `NetworkContext` and the blockchain client reference. /// Creates a new instance from the `NetworkContext` and the blockchain client reference.
pub fn new( pub fn new(
network: &'s NetworkContext, network: &'s dyn NetworkContext,
chain: &'s BlockChainClient, chain: &'s dyn BlockChainClient,
snapshot_service: &'s SnapshotService, snapshot_service: &'s dyn SnapshotService,
chain_overlay: &'s RwLock<HashMap<BlockNumber, Bytes>>, chain_overlay: &'s RwLock<HashMap<BlockNumber, Bytes>>,
) -> NetSyncIo<'s> { ) -> NetSyncIo<'s> {
NetSyncIo { NetSyncIo {
@ -105,7 +105,7 @@ impl<'s> SyncIo for NetSyncIo<'s> {
.send_protocol(packet_id.protocol(), peer_id, packet_id.id(), data) .send_protocol(packet_id.protocol(), peer_id, packet_id.id(), data)
} }
fn chain(&self) -> &BlockChainClient { fn chain(&self) -> &dyn BlockChainClient {
self.chain self.chain
} }
@ -113,7 +113,7 @@ impl<'s> SyncIo for NetSyncIo<'s> {
self.chain_overlay self.chain_overlay
} }
fn snapshot_service(&self) -> &SnapshotService { fn snapshot_service(&self) -> &dyn SnapshotService {
self.snapshot_service self.snapshot_service
} }

View File

@ -49,9 +49,9 @@ fn authority_round() {
let chain_id = Spec::new_test_round().chain_id(); let chain_id = Spec::new_test_round().chain_id();
let mut net = TestNet::with_spec(2, SyncConfig::default(), Spec::new_test_round); let mut net = TestNet::with_spec(2, SyncConfig::default(), Spec::new_test_round);
let io_handler0: Arc<IoHandler<ClientIoMessage>> = let io_handler0: Arc<dyn IoHandler<ClientIoMessage>> =
Arc::new(TestIoHandler::new(net.peer(0).chain.clone())); Arc::new(TestIoHandler::new(net.peer(0).chain.clone()));
let io_handler1: Arc<IoHandler<ClientIoMessage>> = let io_handler1: Arc<dyn IoHandler<ClientIoMessage>> =
Arc::new(TestIoHandler::new(net.peer(1).chain.clone())); Arc::new(TestIoHandler::new(net.peer(1).chain.clone()));
// Push transaction to both clients. Only one of them gets lucky to produce a block. // Push transaction to both clients. Only one of them gets lucky to produce a block.
net.peer(0) net.peer(0)

View File

@ -149,7 +149,7 @@ where
Ok(()) Ok(())
} }
fn chain(&self) -> &BlockChainClient { fn chain(&self) -> &dyn BlockChainClient {
&*self.chain &*self.chain
} }
@ -163,7 +163,7 @@ where
ClientVersion::from(client_id) ClientVersion::from(client_id)
} }
fn snapshot_service(&self) -> &SnapshotService { fn snapshot_service(&self) -> &dyn SnapshotService {
self.snapshot_service self.snapshot_service
} }

View File

@ -58,9 +58,9 @@ fn send_private_transaction() {
let mut net = TestNet::with_spec(2, SyncConfig::default(), seal_spec); let mut net = TestNet::with_spec(2, SyncConfig::default(), seal_spec);
let client0 = net.peer(0).chain.clone(); let client0 = net.peer(0).chain.clone();
let client1 = net.peer(1).chain.clone(); let client1 = net.peer(1).chain.clone();
let io_handler0: Arc<IoHandler<ClientIoMessage>> = let io_handler0: Arc<dyn IoHandler<ClientIoMessage>> =
Arc::new(TestIoHandler::new(net.peer(0).chain.clone())); Arc::new(TestIoHandler::new(net.peer(0).chain.clone()));
let io_handler1: Arc<IoHandler<ClientIoMessage>> = let io_handler1: Arc<dyn IoHandler<ClientIoMessage>> =
Arc::new(TestIoHandler::new(net.peer(1).chain.clone())); Arc::new(TestIoHandler::new(net.peer(1).chain.clone()));
net.peer(0) net.peer(0)

View File

@ -130,5 +130,5 @@ impl fmt::Display for Error {
pub type Result<T> = ::std::result::Result<T, Error>; pub type Result<T> = ::std::result::Result<T, Error>;
pub type TrapResult<T, Call, Create> = ::std::result::Result<Result<T>, TrapError<Call, Create>>; pub type TrapResult<T, Call, Create> = ::std::result::Result<Result<T>, TrapError<Call, Create>>;
pub type ExecTrapResult<T> = TrapResult<T, Box<ResumeCall>, Box<ResumeCreate>>; pub type ExecTrapResult<T> = TrapResult<T, Box<dyn ResumeCall>, Box<dyn ResumeCreate>>;
pub type ExecTrapError = TrapError<Box<ResumeCall>, Box<ResumeCreate>>; pub type ExecTrapError = TrapError<Box<dyn ResumeCall>, Box<dyn ResumeCreate>>;

View File

@ -46,17 +46,17 @@ pub trait Exec: Send {
/// This function should be used to execute transaction. /// This function should be used to execute transaction.
/// It returns either an error, a known amount of gas left, or parameters to be used /// It returns either an error, a known amount of gas left, or parameters to be used
/// to compute the final gas left. /// to compute the final gas left.
fn exec(self: Box<Self>, ext: &mut Ext) -> ExecTrapResult<GasLeft>; fn exec(self: Box<Self>, ext: &mut dyn Ext) -> ExecTrapResult<GasLeft>;
} }
/// Resume call interface /// Resume call interface
pub trait ResumeCall: Send { pub trait ResumeCall: Send {
/// Resume an execution for call, returns back the Vm interface. /// Resume an execution for call, returns back the Vm interface.
fn resume_call(self: Box<Self>, result: MessageCallResult) -> Box<Exec>; fn resume_call(self: Box<Self>, result: MessageCallResult) -> Box<dyn Exec>;
} }
/// Resume create interface /// Resume create interface
pub trait ResumeCreate: Send { pub trait ResumeCreate: Send {
/// Resume an execution from create, returns back the Vm interface. /// Resume an execution from create, returns back the Vm interface.
fn resume_create(self: Box<Self>, result: ContractCreateResult) -> Box<Exec>; fn resume_create(self: Box<Self>, result: ContractCreateResult) -> Box<dyn Exec>;
} }

View File

@ -136,7 +136,7 @@ impl fmt::Display for Fail {
} }
pub fn construct( pub fn construct(
ext: &mut vm::Ext, ext: &mut dyn vm::Ext,
source: Vec<u8>, source: Vec<u8>,
arguments: Vec<u8>, arguments: Vec<u8>,
sender: H160, sender: H160,

View File

@ -96,7 +96,7 @@ enum ExecutionOutcome {
} }
impl WasmInterpreter { impl WasmInterpreter {
pub fn run(self: Box<WasmInterpreter>, ext: &mut vm::Ext) -> vm::Result<GasLeft> { pub fn run(self: Box<WasmInterpreter>, ext: &mut dyn vm::Ext) -> vm::Result<GasLeft> {
let (module, data) = parser::payload(&self.params, ext.schedule().wasm())?; let (module, data) = parser::payload(&self.params, ext.schedule().wasm())?;
let loaded_module = let loaded_module =
@ -204,7 +204,7 @@ impl WasmInterpreter {
} }
impl vm::Exec for WasmInterpreter { impl vm::Exec for WasmInterpreter {
fn exec(self: Box<WasmInterpreter>, ext: &mut vm::Ext) -> vm::ExecTrapResult<GasLeft> { fn exec(self: Box<WasmInterpreter>, ext: &mut dyn vm::Ext) -> vm::ExecTrapResult<GasLeft> {
Ok(self.run(ext)) Ok(self.run(ext))
} }
} }

View File

@ -33,7 +33,7 @@ pub struct RuntimeContext {
pub struct Runtime<'a> { pub struct Runtime<'a> {
gas_counter: u64, gas_counter: u64,
gas_limit: u64, gas_limit: u64,
ext: &'a mut vm::Ext, ext: &'a mut dyn vm::Ext,
context: RuntimeContext, context: RuntimeContext,
memory: MemoryRef, memory: MemoryRef,
args: Vec<u8>, args: Vec<u8>,
@ -149,7 +149,7 @@ type Result<T> = ::std::result::Result<T, Error>;
impl<'a> Runtime<'a> { impl<'a> Runtime<'a> {
/// New runtime for wasm contract with specified params /// New runtime for wasm contract with specified params
pub fn with_params( pub fn with_params(
ext: &mut vm::Ext, ext: &mut dyn vm::Ext,
memory: MemoryRef, memory: MemoryRef,
gas_limit: u64, gas_limit: u64,
args: Vec<u8>, args: Vec<u8>,

Some files were not shown because too many files have changed in this diff Show More