From dab2a6bd4b340f4dbe13207fea33f1081ab9f2ec Mon Sep 17 00:00:00 2001 From: Niklas Adolfsson Date: Tue, 27 Aug 2019 17:29:33 +0200 Subject: [PATCH 1/7] fix compile warnings (#10993) * fix warnings * fix: failing build, use `spec` as dev-dependency --- accounts/ethstore/src/accounts_dir/disk.rs | 6 ++--- accounts/ethstore/src/accounts_dir/mod.rs | 8 +++---- accounts/ethstore/src/accounts_dir/vault.rs | 2 +- accounts/ethstore/src/ethstore.rs | 14 ++++++------ accounts/ethstore/src/import.rs | 6 ++--- accounts/ethstore/src/secret_store.rs | 2 +- accounts/src/lib.rs | 4 ++-- cli-signer/rpc-client/src/lib.rs | 2 +- ethcore/private-tx/src/error.rs | 2 +- ethcore/private-tx/src/lib.rs | 21 +++++++++--------- ethcore/private-tx/src/log.rs | 4 ++-- ethcore/private-tx/src/private_state_db.rs | 6 ++--- ethcore/private-tx/src/state_store.rs | 4 ++-- ethcore/service/src/service.rs | 16 +++++++------- ethcore/sync/src/chain/handler.rs | 2 +- ethcore/sync/src/chain/mod.rs | 2 +- ethcore/sync/src/chain/requester.rs | 2 +- ethcore/sync/src/chain/supplier.rs | 2 +- miner/local-store/src/lib.rs | 10 ++++----- miner/stratum/src/lib.rs | 4 ++-- parity/account_utils.rs | 4 ++-- parity/blockchain.rs | 8 +++---- parity/db/rocksdb/mod.rs | 18 +++++++++------ parity/informant.rs | 6 ++--- parity/ipfs.rs | 2 +- parity/light_helpers/epoch_fetch.rs | 4 ++-- parity/modules.rs | 22 +++++++++---------- parity/rpc_apis.rs | 10 ++++----- parity/run.rs | 12 +++++----- parity/secretstore.rs | 2 +- rpc/Cargo.toml | 2 +- rpc/src/lib.rs | 5 ++++- rpc/src/v1/helpers/deprecated.rs | 2 +- rpc/src/v1/helpers/dispatch/full.rs | 2 +- rpc/src/v1/helpers/dispatch/light.rs | 8 +++---- rpc/src/v1/helpers/dispatch/mod.rs | 4 ++-- .../v1/helpers/dispatch/prospective_signer.rs | 4 ++-- rpc/src/v1/helpers/external_signer/mod.rs | 2 +- .../helpers/external_signer/signing_queue.rs | 2 +- rpc/src/v1/helpers/light_fetch.rs | 12 +++++----- rpc/src/v1/helpers/subscription_manager.rs | 2 +- rpc/src/v1/impls/eth.rs | 8 +++---- rpc/src/v1/impls/eth_pubsub.rs | 2 +- rpc/src/v1/impls/light/eth.rs | 4 ++-- rpc/src/v1/impls/light/parity_set.rs | 6 ++--- rpc/src/v1/impls/parity.rs | 12 +++++----- rpc/src/v1/impls/parity_set.rs | 4 ++-- rpc/src/v1/impls/signer.rs | 6 ++--- rpc/src/v1/impls/signing.rs | 4 ++-- rpc/src/v1/impls/signing_unsafe.rs | 4 ++-- rpc/src/v1/tests/helpers/miner_service.rs | 4 ++-- rpc/src/v1/tests/mocked/manage_network.rs | 2 +- rpc/src/v1/tests/mocked/parity.rs | 2 +- rpc/src/v1/tests/mocked/parity_set.rs | 2 +- rpc/src/v1/types/derivation.rs | 2 +- updater/hash-fetch/src/client.rs | 8 +++---- updater/hash-fetch/src/lib.rs | 2 +- updater/hash-fetch/src/urlhint.rs | 8 +++---- updater/src/lib.rs | 3 +-- updater/src/updater.rs | 18 +++++++-------- util/EIP-712/src/error.rs | 2 +- util/fetch/src/client.rs | 4 ++-- util/migration-rocksdb/src/lib.rs | 6 ++--- util/network-devp2p/src/ip_utils.rs | 8 +++---- util/network/src/error.rs | 2 +- util/network/src/lib.rs | 12 +++++----- util/registrar/src/lib.rs | 3 +-- util/registrar/src/registrar.rs | 8 +++---- util/rlp-compress/src/lib.rs | 4 ++-- 69 files changed, 203 insertions(+), 199 deletions(-) diff --git a/accounts/ethstore/src/accounts_dir/disk.rs b/accounts/ethstore/src/accounts_dir/disk.rs index 4cc8611bfdd..b70029785e7 100644 --- a/accounts/ethstore/src/accounts_dir/disk.rs +++ b/accounts/ethstore/src/accounts_dir/disk.rs @@ -284,7 +284,7 @@ impl KeyDirectory for DiskDirectory where T: KeyFileManager { fn path(&self) -> Option<&PathBuf> { Some(&self.path) } - fn as_vault_provider(&self) -> Option<&VaultKeyDirectoryProvider> { + fn as_vault_provider(&self) -> Option<&dyn VaultKeyDirectoryProvider> { Some(self) } @@ -294,12 +294,12 @@ impl KeyDirectory for DiskDirectory where T: KeyFileManager { } impl VaultKeyDirectoryProvider for DiskDirectory where T: KeyFileManager { - fn create(&self, name: &str, key: VaultKey) -> Result, Error> { + fn create(&self, name: &str, key: VaultKey) -> Result, Error> { let vault_dir = VaultDiskDirectory::create(&self.path, name, key)?; Ok(Box::new(vault_dir)) } - fn open(&self, name: &str, key: VaultKey) -> Result, Error> { + fn open(&self, name: &str, key: VaultKey) -> Result, Error> { let vault_dir = VaultDiskDirectory::at(&self.path, name, key)?; Ok(Box::new(vault_dir)) } diff --git a/accounts/ethstore/src/accounts_dir/mod.rs b/accounts/ethstore/src/accounts_dir/mod.rs index 300c395222d..93a6879bac0 100644 --- a/accounts/ethstore/src/accounts_dir/mod.rs +++ b/accounts/ethstore/src/accounts_dir/mod.rs @@ -57,7 +57,7 @@ pub trait KeyDirectory: Send + Sync { /// Get directory filesystem path, if available fn path(&self) -> Option<&PathBuf> { None } /// Return vault provider, if available - fn as_vault_provider(&self) -> Option<&VaultKeyDirectoryProvider> { None } + fn as_vault_provider(&self) -> Option<&dyn VaultKeyDirectoryProvider> { None } /// Unique representation of directory account collection fn unique_repr(&self) -> Result; } @@ -65,9 +65,9 @@ pub trait KeyDirectory: Send + Sync { /// Vaults provider pub trait VaultKeyDirectoryProvider { /// Create new vault with given key - fn create(&self, name: &str, key: VaultKey) -> Result, Error>; + fn create(&self, name: &str, key: VaultKey) -> Result, Error>; /// Open existing vault with given key - fn open(&self, name: &str, key: VaultKey) -> Result, Error>; + fn open(&self, name: &str, key: VaultKey) -> Result, Error>; /// List all vaults fn list_vaults(&self) -> Result, Error>; /// Get vault meta @@ -77,7 +77,7 @@ pub trait VaultKeyDirectoryProvider { /// Vault directory pub trait VaultKeyDirectory: KeyDirectory { /// Cast to `KeyDirectory` - fn as_key_directory(&self) -> &KeyDirectory; + fn as_key_directory(&self) -> &dyn KeyDirectory; /// Vault name fn name(&self) -> &str; /// Get vault key diff --git a/accounts/ethstore/src/accounts_dir/vault.rs b/accounts/ethstore/src/accounts_dir/vault.rs index 1aea7e104c1..feab2b35698 100644 --- a/accounts/ethstore/src/accounts_dir/vault.rs +++ b/accounts/ethstore/src/accounts_dir/vault.rs @@ -119,7 +119,7 @@ impl VaultDiskDirectory { } impl VaultKeyDirectory for VaultDiskDirectory { - fn as_key_directory(&self) -> &KeyDirectory { + fn as_key_directory(&self) -> &dyn KeyDirectory { self } diff --git a/accounts/ethstore/src/ethstore.rs b/accounts/ethstore/src/ethstore.rs index 6fce9ae62e7..89bb14ba611 100644 --- a/accounts/ethstore/src/ethstore.rs +++ b/accounts/ethstore/src/ethstore.rs @@ -36,12 +36,12 @@ pub struct EthStore { impl EthStore { /// Open a new accounts store with given key directory backend. - pub fn open(directory: Box) -> Result { + pub fn open(directory: Box) -> Result { Self::open_with_iterations(directory, KEY_ITERATIONS as u32) } /// Open a new account store with given key directory backend and custom number of iterations. - pub fn open_with_iterations(directory: Box, iterations: u32) -> Result { + pub fn open_with_iterations(directory: Box, iterations: u32) -> Result { Ok(EthStore { store: EthMultiStore::open_with_iterations(directory, iterations)?, }) @@ -184,7 +184,7 @@ impl SecretStore for EthStore { Ok(account.check_password(password)) } - fn copy_account(&self, new_store: &SimpleSecretStore, new_vault: SecretVaultRef, account: &StoreAccountRef, password: &Password, new_password: &Password) -> Result<(), Error> { + fn copy_account(&self, new_store: &dyn SimpleSecretStore, new_vault: SecretVaultRef, account: &StoreAccountRef, password: &Password, new_password: &Password) -> Result<(), Error> { let account = self.get(account)?; let secret = account.crypto.secret(password)?; new_store.insert_account(new_vault, secret, new_password)?; @@ -256,11 +256,11 @@ impl SecretStore for EthStore { /// Similar to `EthStore` but may store many accounts (with different passwords) for the same `Address` pub struct EthMultiStore { - dir: Box, + dir: Box, iterations: u32, // order lock: cache, then vaults cache: RwLock>>, - vaults: Mutex>>, + vaults: Mutex>>, timestamp: Mutex, } @@ -272,12 +272,12 @@ struct Timestamp { impl EthMultiStore { /// Open new multi-accounts store with given key directory backend. - pub fn open(directory: Box) -> Result { + pub fn open(directory: Box) -> Result { Self::open_with_iterations(directory, KEY_ITERATIONS as u32) } /// Open new multi-accounts store with given key directory backend and custom number of iterations for new keys. - pub fn open_with_iterations(directory: Box, iterations: u32) -> Result { + pub fn open_with_iterations(directory: Box, iterations: u32) -> Result { let store = EthMultiStore { dir: directory, vaults: Mutex::new(HashMap::new()), diff --git a/accounts/ethstore/src/import.rs b/accounts/ethstore/src/import.rs index 87e9783eae7..3fe9763e8f2 100644 --- a/accounts/ethstore/src/import.rs +++ b/accounts/ethstore/src/import.rs @@ -24,7 +24,7 @@ use dir; use Error; /// Import an account from a file. -pub fn import_account(path: &Path, dst: &KeyDirectory) -> Result { +pub fn import_account(path: &Path, dst: &dyn KeyDirectory) -> Result { let key_manager = DiskKeyFileManager::default(); let existing_accounts = dst.load()?.into_iter().map(|a| a.address).collect::>(); let filename = path.file_name().and_then(|n| n.to_str()).map(|f| f.to_owned()); @@ -40,7 +40,7 @@ pub fn import_account(path: &Path, dst: &KeyDirectory) -> Result } /// Import all accounts from one directory to the other. -pub fn import_accounts(src: &KeyDirectory, dst: &KeyDirectory) -> Result, Error> { +pub fn import_accounts(src: &dyn KeyDirectory, dst: &dyn KeyDirectory) -> Result, Error> { let accounts = src.load()?; let existing_accounts = dst.load()?.into_iter() .map(|a| a.address) @@ -64,7 +64,7 @@ pub fn read_geth_accounts(testnet: bool) -> Vec
{ } /// Import specific `desired` accounts from the Geth keystore into `dst`. -pub fn import_geth_accounts(dst: &KeyDirectory, desired: HashSet
, testnet: bool) -> Result, Error> { +pub fn import_geth_accounts(dst: &dyn KeyDirectory, desired: HashSet
, testnet: bool) -> Result, Error> { let src = RootDiskDirectory::at(dir::geth(testnet)); let accounts = src.load()?; let existing_accounts = dst.load()?.into_iter().map(|a| a.address).collect::>(); diff --git a/accounts/ethstore/src/secret_store.rs b/accounts/ethstore/src/secret_store.rs index 5571f83c0cd..d3ca1a12fba 100644 --- a/accounts/ethstore/src/secret_store.rs +++ b/accounts/ethstore/src/secret_store.rs @@ -118,7 +118,7 @@ pub trait SecretStore: SimpleSecretStore { /// Imports existing JSON wallet fn import_wallet(&self, vault: SecretVaultRef, json: &[u8], password: &Password, gen_id: bool) -> Result; /// Copies account between stores and vaults. - fn copy_account(&self, new_store: &SimpleSecretStore, new_vault: SecretVaultRef, account: &StoreAccountRef, password: &Password, new_password: &Password) -> Result<(), Error>; + fn copy_account(&self, new_store: &dyn SimpleSecretStore, new_vault: SecretVaultRef, account: &StoreAccountRef, password: &Password, new_password: &Password) -> Result<(), Error>; /// Checks if password matches given account. fn test_password(&self, account: &StoreAccountRef, password: &Password) -> Result; diff --git a/accounts/src/lib.rs b/accounts/src/lib.rs index 9f31e8f536e..ac87a2ee332 100644 --- a/accounts/src/lib.rs +++ b/accounts/src/lib.rs @@ -64,7 +64,7 @@ pub struct AccountProvider { /// Address book. address_book: RwLock, /// Accounts on disk - sstore: Box, + sstore: Box, /// Accounts unlocked with rolling tokens transient_sstore: EthMultiStore, /// When unlocking account permanently we additionally keep a raw secret in memory @@ -80,7 +80,7 @@ fn transient_sstore() -> EthMultiStore { impl AccountProvider { /// Creates new account provider. - pub fn new(sstore: Box, settings: AccountProviderSettings) -> Self { + pub fn new(sstore: Box, settings: AccountProviderSettings) -> Self { if let Ok(accounts) = sstore.accounts() { for account in accounts.into_iter().filter(|a| settings.blacklisted_accounts.contains(&a.address)) { warn!("Local Account {} has a blacklisted (known to be weak) address and will be ignored", diff --git a/cli-signer/rpc-client/src/lib.rs b/cli-signer/rpc-client/src/lib.rs index d0e087e59d9..fe945c7f7df 100644 --- a/cli-signer/rpc-client/src/lib.rs +++ b/cli-signer/rpc-client/src/lib.rs @@ -36,7 +36,7 @@ extern crate log; extern crate matches; /// Boxed future response. -pub type BoxFuture = Box + Send>; +pub type BoxFuture = Box + Send>; #[cfg(test)] mod tests { diff --git a/ethcore/private-tx/src/error.rs b/ethcore/private-tx/src/error.rs index dada209246b..b9167675ff0 100644 --- a/ethcore/private-tx/src/error.rs +++ b/ethcore/private-tx/src/error.rs @@ -138,7 +138,7 @@ pub enum Error { } impl error::Error for Error { - fn source(&self) -> Option<&(error::Error + 'static)> { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self { Error::Io(e) => Some(e), Error::Decoder(e) => Some(e), diff --git a/ethcore/private-tx/src/lib.rs b/ethcore/private-tx/src/lib.rs index 087f85b63d7..2368205baf8 100644 --- a/ethcore/private-tx/src/lib.rs +++ b/ethcore/private-tx/src/lib.rs @@ -63,7 +63,6 @@ extern crate transaction_pool as txpool; extern crate url; #[macro_use] extern crate log as ethlog; -#[macro_use] extern crate ethabi_derive; #[macro_use] extern crate ethabi_contract; @@ -205,17 +204,17 @@ impl Signer for KeyPairSigner { /// Manager of private transactions pub struct Provider { - encryptor: Box, + encryptor: Box, validator_accounts: HashSet
, signer_account: Option
, - notify: RwLock>>, + notify: RwLock>>, transactions_for_signing: RwLock, transactions_for_verification: VerificationStore, client: Arc, miner: Arc, - accounts: Arc, + accounts: Arc, channel: IoChannel, - keys_provider: Arc, + keys_provider: Arc, logging: Option, use_offchain_storage: bool, state_storage: PrivateStateStorage, @@ -234,12 +233,12 @@ impl Provider { pub fn new( client: Arc, miner: Arc, - accounts: Arc, - encryptor: Box, + accounts: Arc, + encryptor: Box, config: ProviderConfig, channel: IoChannel, - keys_provider: Arc, - db: Arc, + keys_provider: Arc, + db: Arc, ) -> Self { keys_provider.update_acl_contract(); Provider { @@ -268,11 +267,11 @@ impl Provider { // TODO [ToDr] Don't use `ChainNotify` here! // Better to create a separate notification type for this. /// Adds an actor to be notified on certain events - pub fn add_notify(&self, target: Arc) { + pub fn add_notify(&self, target: Arc) { self.notify.write().push(Arc::downgrade(&target)); } - fn notify(&self, f: F) where F: Fn(&ChainNotify) { + fn notify(&self, f: F) where F: Fn(&dyn ChainNotify) { for np in self.notify.read().iter() { if let Some(n) = np.upgrade() { f(&*n); diff --git a/ethcore/private-tx/src/log.rs b/ethcore/private-tx/src/log.rs index 0d09797529e..6c1f8819c9d 100644 --- a/ethcore/private-tx/src/log.rs +++ b/ethcore/private-tx/src/log.rs @@ -186,13 +186,13 @@ impl LogsSerializer for FileLogsSerializer { /// Private transactions logging pub struct Logging { logs: RwLock>, - logs_serializer: Arc, + logs_serializer: Arc, mono_time: MonoTime, } impl Logging { /// Creates the logging object - pub fn new(logs_serializer: Arc) -> Self { + pub fn new(logs_serializer: Arc) -> Self { let mut logging = Logging { logs: RwLock::new(HashMap::new()), logs_serializer, diff --git a/ethcore/private-tx/src/private_state_db.rs b/ethcore/private-tx/src/private_state_db.rs index a701f7330ef..44f78725596 100644 --- a/ethcore/private-tx/src/private_state_db.rs +++ b/ethcore/private-tx/src/private_state_db.rs @@ -25,12 +25,12 @@ use error::Error; /// Wrapper around local db with private state for sync purposes pub struct PrivateStateDB { - db: Arc, + db: Arc, } impl PrivateStateDB { /// Constructs the object - pub fn new(db: Arc) -> Self { + pub fn new(db: Arc) -> Self { PrivateStateDB { db, } @@ -59,4 +59,4 @@ impl PrivateStateDB { pub fn state_hash(&self, state: &Bytes) -> Result { Ok(KeccakHasher::hash(state)) } -} \ No newline at end of file +} diff --git a/ethcore/private-tx/src/state_store.rs b/ethcore/private-tx/src/state_store.rs index 002dca36505..2b550e3517e 100644 --- a/ethcore/private-tx/src/state_store.rs +++ b/ethcore/private-tx/src/state_store.rs @@ -57,7 +57,7 @@ pub struct PrivateStateStorage { impl PrivateStateStorage { /// Constructs the object - pub fn new(db: Arc) -> Self { + pub fn new(db: Arc) -> Self { PrivateStateStorage { private_state_db: Arc::new(PrivateStateDB::new(db)), requests: RwLock::new(Vec::new()), @@ -162,4 +162,4 @@ impl PrivateStateStorage { !delete_request }); } -} \ No newline at end of file +} diff --git a/ethcore/service/src/service.rs b/ethcore/service/src/service.rs index c1aebfe93f5..a1bda778b80 100644 --- a/ethcore/service/src/service.rs +++ b/ethcore/service/src/service.rs @@ -94,7 +94,7 @@ pub struct ClientService { client: Arc, snapshot: Arc, private_tx: Arc, - database: Arc, + database: Arc, } impl ClientService { @@ -102,13 +102,13 @@ impl ClientService { pub fn start( config: ClientConfig, spec: &Spec, - blockchain_db: Arc, + blockchain_db: Arc, snapshot_path: &Path, - restoration_db_handler: Box, + restoration_db_handler: Box, _ipc_path: &Path, miner: Arc, - signer: Arc, - encryptor: Box, + signer: Arc, + encryptor: Box, private_tx_conf: ethcore_private_tx::ProviderConfig, private_encryptor_conf: ethcore_private_tx::EncryptorConfig, ) -> Result @@ -173,7 +173,7 @@ impl ClientService { } /// Get general IO interface - pub fn register_io_handler(&self, handler: Arc + Send>) -> Result<(), IoError> { + pub fn register_io_handler(&self, handler: Arc + Send>) -> Result<(), IoError> { self.io_service.register_handler(handler) } @@ -198,12 +198,12 @@ impl ClientService { } /// Set the actor to be notified on certain chain events - pub fn add_notify(&self, notify: Arc) { + pub fn add_notify(&self, notify: Arc) { self.client.add_notify(notify); } /// Get a handle to the database. - pub fn db(&self) -> Arc { self.database.clone() } + pub fn db(&self) -> Arc { self.database.clone() } /// Shutdown the Client Service pub fn shutdown(&self) { diff --git a/ethcore/sync/src/chain/handler.rs b/ethcore/sync/src/chain/handler.rs index 89c740951c1..e7a54fa95be 100644 --- a/ethcore/sync/src/chain/handler.rs +++ b/ethcore/sync/src/chain/handler.rs @@ -743,7 +743,7 @@ impl SyncHandler { Ok(()) } - fn on_private_state_data(sync: &mut ChainSync, io: &mut SyncIo, peer_id: PeerId, r: &Rlp) -> Result<(), DownloaderImportError> { + fn on_private_state_data(sync: &mut ChainSync, io: &mut dyn SyncIo, peer_id: PeerId, r: &Rlp) -> Result<(), DownloaderImportError> { if !sync.peers.get(&peer_id).map_or(false, |p| p.can_sync()) { trace!(target: "sync", "{} Ignoring packet from unconfirmed/unknown peer", peer_id); return Ok(()); diff --git a/ethcore/sync/src/chain/mod.rs b/ethcore/sync/src/chain/mod.rs index 233a41b5f49..07be14f7fe0 100644 --- a/ethcore/sync/src/chain/mod.rs +++ b/ethcore/sync/src/chain/mod.rs @@ -1382,7 +1382,7 @@ impl ChainSync { } /// Request private state from peers - pub fn request_private_state(&mut self, io: &mut SyncIo, hash: &H256) { + pub fn request_private_state(&mut self, io: &mut dyn SyncIo, hash: &H256) { let private_state_peers = self.get_private_state_peers(); if private_state_peers.is_empty() { error!(target: "privatetx", "Cannot request private state, no peers with private tx enabled available"); diff --git a/ethcore/sync/src/chain/requester.rs b/ethcore/sync/src/chain/requester.rs index b47c3930149..e79de22929d 100644 --- a/ethcore/sync/src/chain/requester.rs +++ b/ethcore/sync/src/chain/requester.rs @@ -100,7 +100,7 @@ impl SyncRequester { SyncRequester::send_request(sync, io, peer_id, PeerAsking::SnapshotManifest, GetSnapshotManifestPacket, rlp.out()); } - pub fn request_private_state(sync: &mut ChainSync, io: &mut SyncIo, peer_id: PeerId, hash: &H256) { + pub fn request_private_state(sync: &mut ChainSync, io: &mut dyn SyncIo, peer_id: PeerId, hash: &H256) { trace!(target: "privatetx", "{} <- GetPrivateStatePacket", peer_id); let mut rlp = RlpStream::new_list(1); rlp.append(hash); diff --git a/ethcore/sync/src/chain/supplier.rs b/ethcore/sync/src/chain/supplier.rs index a6a95f07a12..fe09766bf8e 100644 --- a/ethcore/sync/src/chain/supplier.rs +++ b/ethcore/sync/src/chain/supplier.rs @@ -356,7 +356,7 @@ impl SyncSupplier { } /// Respond to GetPrivateStatePacket - fn return_private_state(io: &SyncIo, r: &Rlp, peer_id: PeerId) -> RlpResponseResult { + fn return_private_state(io: &dyn SyncIo, r: &Rlp, peer_id: PeerId) -> RlpResponseResult { let hash: H256 = r.val_at(0)?; trace!(target: "privatetx", "{} -> GetPrivateStatePacket {:?}", peer_id, hash); io.private_state().map_or(Ok(None), |db| { diff --git a/miner/local-store/src/lib.rs b/miner/local-store/src/lib.rs index 1c0811b4d87..7c3a12776b3 100644 --- a/miner/local-store/src/lib.rs +++ b/miner/local-store/src/lib.rs @@ -107,11 +107,11 @@ pub trait NodeInfo: Send + Sync { /// Create a new local data store, given a database, a column to write to, and a node. /// Attempts to read data out of the store, and move it into the node. -pub fn create(db: Arc, col: Option, node: T) -> LocalDataStore { +pub fn create(db: Arc, col: Option, node: T) -> LocalDataStore { LocalDataStore { - db: db, - col: col, - node: node, + db, + col, + node, } } @@ -120,7 +120,7 @@ pub fn create(db: Arc, col: Option, node: T) -> Lo /// In specific, this will be used to store things like unpropagated local transactions /// and the node security level. pub struct LocalDataStore { - db: Arc, + db: Arc, col: Option, node: T, } diff --git a/miner/stratum/src/lib.rs b/miner/stratum/src/lib.rs index 5ee0296dacf..cb2eca13e72 100644 --- a/miner/stratum/src/lib.rs +++ b/miner/stratum/src/lib.rs @@ -70,7 +70,7 @@ pub struct Stratum { impl Stratum { pub fn start( addr: &SocketAddr, - dispatcher: Arc, + dispatcher: Arc, secret: Option, ) -> Result, Error> { @@ -128,7 +128,7 @@ struct StratumImpl { /// List of workers supposed to receive job update job_que: RwLock>, /// Payload manager - dispatcher: Arc, + dispatcher: Arc, /// Authorized workers (socket - worker_id) workers: Arc>>, /// Secret if any diff --git a/parity/account_utils.rs b/parity/account_utils.rs index 9c380c2f56e..4f65336315d 100644 --- a/parity/account_utils.rs +++ b/parity/account_utils.rs @@ -199,14 +199,14 @@ mod accounts { } } - pub fn private_tx_signer(accounts: Arc, passwords: &[Password]) -> Result, String> { + pub fn private_tx_signer(accounts: Arc, passwords: &[Password]) -> Result, String> { Ok(Arc::new(self::private_tx::AccountSigner { accounts, passwords: passwords.to_vec(), })) } - pub fn accounts_list(account_provider: Arc) -> Arc Vec
+ Send + Sync> { + pub fn accounts_list(account_provider: Arc) -> Arc Vec
+ Send + Sync> { Arc::new(move || account_provider.accounts().unwrap_or_default()) } diff --git a/parity/blockchain.rs b/parity/blockchain.rs index d5e66676803..85000e385c1 100644 --- a/parity/blockchain.rs +++ b/parity/blockchain.rs @@ -244,7 +244,7 @@ fn execute_import_light(cmd: ImportBlockchain) -> Result<(), String> { let client = service.client(); - let mut instream: Box = match cmd.file_path { + let mut instream: Box = match cmd.file_path { Some(f) => Box::new(fs::File::open(&f).map_err(|_| format!("Cannot open given file: {}", f))?), None => Box::new(io::stdin()), }; @@ -412,7 +412,7 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> { let client = service.client(); - let mut instream: Box = match cmd.file_path { + let mut instream: Box = match cmd.file_path { Some(f) => Box::new(fs::File::open(&f).map_err(|_| format!("Cannot open given file: {}", f))?), None => Box::new(io::stdin()), }; @@ -621,7 +621,7 @@ fn execute_export(cmd: ExportBlockchain) -> Result<(), String> { let client = service.client(); - let mut out: Box = match cmd.file_path { + let mut out: Box = match cmd.file_path { Some(f) => Box::new(fs::File::create(&f).map_err(|_| format!("Cannot write to file given: {}", f))?), None => Box::new(io::stdout()), }; @@ -665,7 +665,7 @@ fn execute_export_state(cmd: ExportState) -> Result<(), String> { let client = service.client(); - let mut out: Box = match cmd.file_path { + let mut out: Box = match cmd.file_path { Some(f) => Box::new(fs::File::create(&f).map_err(|_| format!("Cannot write to file given: {}", f))?), None => Box::new(io::stdout()), }; diff --git a/parity/db/rocksdb/mod.rs b/parity/db/rocksdb/mod.rs index c7aa0a5344d..bf56b4d29ee 100644 --- a/parity/db/rocksdb/mod.rs +++ b/parity/db/rocksdb/mod.rs @@ -37,13 +37,13 @@ mod helpers; pub use self::migration::migrate; struct AppDB { - key_value: Arc, + key_value: Arc, blooms: blooms_db::Database, trace_blooms: blooms_db::Database, } impl BlockChainDB for AppDB { - fn key_value(&self) -> &Arc { + fn key_value(&self) -> &Arc { &self.key_value } @@ -58,7 +58,7 @@ impl BlockChainDB for AppDB { /// Open a secret store DB using the given secret store data path. The DB path is one level beneath the data path. #[cfg(feature = "secretstore")] -pub fn open_secretstore_db(data_path: &str) -> Result, String> { +pub fn open_secretstore_db(data_path: &str) -> Result, String> { use std::path::PathBuf; let mut db_path = PathBuf::from(data_path); @@ -68,7 +68,7 @@ pub fn open_secretstore_db(data_path: &str) -> Result, String> { } /// Create a restoration db handler using the config generated by `client_path` and `client_config`. -pub fn restoration_db_handler(client_path: &Path, client_config: &ClientConfig) -> Box { +pub fn restoration_db_handler(client_path: &Path, client_config: &ClientConfig) -> Box { let client_db_config = helpers::client_db_config(client_path, client_config); struct RestorationDBHandler { @@ -76,7 +76,7 @@ pub fn restoration_db_handler(client_path: &Path, client_config: &ClientConfig) } impl BlockChainDBHandler for RestorationDBHandler { - fn open(&self, db_path: &Path) -> io::Result> { + fn open(&self, db_path: &Path) -> io::Result> { open_database(&db_path.to_string_lossy(), &self.config) } } @@ -87,7 +87,11 @@ pub fn restoration_db_handler(client_path: &Path, client_config: &ClientConfig) } /// Open a new main DB. -pub fn open_db(client_path: &str, cache_config: &CacheConfig, compaction: &DatabaseCompactionProfile) -> io::Result> { +pub fn open_db( + client_path: &str, + cache_config: &CacheConfig, + compaction: &DatabaseCompactionProfile +) -> io::Result> { let path = Path::new(client_path); let db_config = DatabaseConfig { @@ -99,7 +103,7 @@ pub fn open_db(client_path: &str, cache_config: &CacheConfig, compaction: &Datab open_database(client_path, &db_config) } -pub fn open_database(client_path: &str, config: &DatabaseConfig) -> io::Result> { +pub fn open_database(client_path: &str, config: &DatabaseConfig) -> io::Result> { let path = Path::new(client_path); let blooms_path = path.join("blooms"); diff --git a/parity/informant.rs b/parity/informant.rs index 0249e60bb12..29a278a2a38 100644 --- a/parity/informant.rs +++ b/parity/informant.rs @@ -124,8 +124,8 @@ pub trait InformantData: Send + Sync { /// Informant data for a full node. pub struct FullNodeInformantData { pub client: Arc, - pub sync: Option>, - pub net: Option>, + pub sync: Option>, + pub net: Option>, } impl InformantData for FullNodeInformantData { @@ -180,7 +180,7 @@ impl InformantData for FullNodeInformantData { /// Informant data for a light node -- note that the network is required. pub struct LightNodeInformantData { - pub client: Arc, + pub client: Arc, pub sync: Arc, pub cache: Arc>, } diff --git a/parity/ipfs.rs b/parity/ipfs.rs index f8062f52a1c..fb2e2f42ae0 100644 --- a/parity/ipfs.rs +++ b/parity/ipfs.rs @@ -40,7 +40,7 @@ impl Default for Configuration { } } -pub fn start_server(conf: Configuration, client: Arc) -> Result, ServerError> { +pub fn start_server(conf: Configuration, client: Arc) -> Result, ServerError> { if !conf.enabled { return Ok(None); } diff --git a/parity/light_helpers/epoch_fetch.rs b/parity/light_helpers/epoch_fetch.rs index f73aec57dcf..faf9b41dcb7 100644 --- a/parity/light_helpers/epoch_fetch.rs +++ b/parity/light_helpers/epoch_fetch.rs @@ -35,7 +35,7 @@ use ethereum_types::H256; const ALL_VALID_BACKREFS: &str = "no back-references, therefore all back-references valid; qed"; -type BoxFuture = Box>; +type BoxFuture = Box>; /// Allows on-demand fetch of data useful for the light client. pub struct EpochFetch { @@ -83,7 +83,7 @@ impl ChainDataFetcher for EpochFetch { } /// Fetch epoch transition proof at given header. - fn epoch_transition(&self, hash: H256, engine: Arc, checker: Arc) + fn epoch_transition(&self, hash: H256, engine: Arc, checker: Arc) -> Self::Transition { self.request(request::Signal { diff --git a/parity/modules.rs b/parity/modules.rs index 7b56fa6d5f3..783d6fcb177 100644 --- a/parity/modules.rs +++ b/parity/modules.rs @@ -28,9 +28,9 @@ pub use ethcore::client::ChainNotify; use ethcore_logger::Config as LogConfig; pub type SyncModules = ( - Arc, - Arc, - Arc, + Arc, + Arc, + Arc, mpsc::Sender, ); @@ -38,13 +38,13 @@ pub fn sync( config: SyncConfig, executor: Executor, network_config: NetworkConfiguration, - chain: Arc, - snapshot_service: Arc, - private_tx_handler: Option>, + chain: Arc, + snapshot_service: Arc, + private_tx_handler: Option>, private_state: Option>, - provider: Arc, + provider: Arc, _log_settings: &LogConfig, - connection_filter: Option>, + connection_filter: Option>, ) -> Result { let eth_sync = EthSync::new(Params { config, @@ -59,9 +59,9 @@ pub fn sync( connection_filter)?; Ok(( - eth_sync.clone() as Arc, - eth_sync.clone() as Arc, - eth_sync.clone() as Arc, + eth_sync.clone() as Arc, + eth_sync.clone() as Arc, + eth_sync.clone() as Arc, eth_sync.priority_tasks() )) } diff --git a/parity/rpc_apis.rs b/parity/rpc_apis.rs index 0b9d4d9f58b..35e65c8ada9 100644 --- a/parity/rpc_apis.rs +++ b/parity/rpc_apis.rs @@ -235,16 +235,16 @@ pub trait Dependencies { pub struct FullDependencies { pub signer_service: Arc, pub client: Arc, - pub snapshot: Arc, - pub sync: Arc, - pub net: Arc, + pub snapshot: Arc, + pub sync: Arc, + pub net: Arc, pub accounts: Arc, pub private_tx_service: Option>, pub miner: Arc, pub external_miner: Arc, pub logger: Arc, pub settings: Arc, - pub net_service: Arc, + pub net_service: Arc, pub updater: Arc, pub geth_compatibility: bool, pub experimental_rpcs: bool, @@ -485,7 +485,7 @@ pub struct LightDependencies { pub signer_service: Arc, pub client: Arc, pub sync: Arc, - pub net: Arc, + pub net: Arc, pub accounts: Arc, pub logger: Arc, pub settings: Arc, diff --git a/parity/run.rs b/parity/run.rs index 417f544f1e4..e53e5b29394 100644 --- a/parity/run.rs +++ b/parity/run.rs @@ -583,7 +583,7 @@ fn execute_impl(cmd: RunCmd, logger: Arc, on_client_rq: // take handle to private transactions service let private_tx_service = service.private_tx_service(); let private_tx_provider = private_tx_service.provider(); - let connection_filter = connection_filter_address.map(|a| Arc::new(NodeFilter::new(Arc::downgrade(&client) as Weak, a))); + let connection_filter = connection_filter_address.map(|a| Arc::new(NodeFilter::new(Arc::downgrade(&client) as Weak, a))); let snapshot_service = service.snapshot_service(); if let Some(filter) = connection_filter.clone() { service.add_notify(filter.clone()); @@ -636,7 +636,7 @@ fn execute_impl(cmd: RunCmd, logger: Arc, on_client_rq: } let (private_tx_sync, private_state) = match cmd.private_tx_enabled { - true => (Some(private_tx_service.clone() as Arc), Some(private_tx_provider.private_state_db())), + true => (Some(private_tx_service.clone() as Arc), Some(private_tx_provider.private_state_db())), false => (None, None), }; @@ -651,7 +651,7 @@ fn execute_impl(cmd: RunCmd, logger: Arc, on_client_rq: private_state, client.clone(), &cmd.logger_config, - connection_filter.clone().map(|f| f as Arc<::sync::ConnectionFilter + 'static>), + connection_filter.clone().map(|f| f as Arc), ).map_err(|e| format!("Sync error: {}", e))?; service.add_notify(chain_notify.clone()); @@ -706,7 +706,7 @@ fn execute_impl(cmd: RunCmd, logger: Arc, on_client_rq: // the updater service let updater_fetch = fetch.clone(); let updater = Updater::new( - &Arc::downgrade(&(service.client() as Arc)), + &Arc::downgrade(&(service.client() as Arc)), &Arc::downgrade(&sync_provider), update_policy, hash_fetch::Client::with_fetch(contract_client.clone(), updater_fetch, runtime.executor()) @@ -843,14 +843,14 @@ enum RunningClientInner { rpc: jsonrpc_core::MetaIoHandler>, informant: Arc>, client: Arc, - keep_alive: Box, + keep_alive: Box, }, Full { rpc: jsonrpc_core::MetaIoHandler>, informant: Arc>, client: Arc, client_service: Arc, - keep_alive: Box, + keep_alive: Box, }, } diff --git a/parity/secretstore.rs b/parity/secretstore.rs index bde67e34422..27424e2752b 100644 --- a/parity/secretstore.rs +++ b/parity/secretstore.rs @@ -93,7 +93,7 @@ pub struct Dependencies<'a> { /// Blockchain client. pub client: Arc, /// Sync provider. - pub sync: Arc, + pub sync: Arc, /// Miner service. pub miner: Arc, /// Account provider. diff --git a/rpc/Cargo.toml b/rpc/Cargo.toml index c5e7dd28baf..fead96d71c5 100644 --- a/rpc/Cargo.toml +++ b/rpc/Cargo.toml @@ -64,7 +64,6 @@ parity-updater = { path = "../updater" } parity-version = { path = "../util/version" } rlp = "0.4.0" account-state = { path = "../ethcore/account-state" } -spec = { path = "../ethcore/spec" } stats = { path = "../util/stats" } trace = { path = "../ethcore/trace" } vm = { path = "../ethcore/vm" } @@ -77,6 +76,7 @@ ethcore-io = { path = "../util/io" } ethcore-network = { path = "../util/network" } fake-fetch = { path = "../util/fake-fetch" } macros = { path = "../util/macros" } +spec = { path = "../ethcore/spec" } pretty_assertions = "0.1" transaction-pool = "2.0" diff --git a/rpc/src/lib.rs b/rpc/src/lib.rs index ed909484f2b..648ec43bf82 100644 --- a/rpc/src/lib.rs +++ b/rpc/src/lib.rs @@ -85,7 +85,7 @@ extern crate parity_version as version; extern crate eip_712; extern crate rlp; extern crate account_state; -extern crate spec; + extern crate stats; extern crate tempdir; extern crate trace; @@ -127,6 +127,9 @@ extern crate fake_fetch; #[cfg(test)] extern crate ethcore_io as io; +#[cfg(test)] +extern crate spec; + pub extern crate jsonrpc_ws_server as ws; mod authcodes; diff --git a/rpc/src/v1/helpers/deprecated.rs b/rpc/src/v1/helpers/deprecated.rs index 49e9d8b0742..8a8ead0d4d3 100644 --- a/rpc/src/v1/helpers/deprecated.rs +++ b/rpc/src/v1/helpers/deprecated.rs @@ -38,7 +38,7 @@ const PRINT_INTERVAL: Duration = Duration::from_secs(60); pub struct DeprecationNotice Instant> { now: T, next_warning_at: RwLock>, - printer: Box) + Send + Sync>, + printer: Box) + Send + Sync>, } impl Default for DeprecationNotice { diff --git a/rpc/src/v1/helpers/dispatch/full.rs b/rpc/src/v1/helpers/dispatch/full.rs index 8c23f720822..2a81e468cfe 100644 --- a/rpc/src/v1/helpers/dispatch/full.rs +++ b/rpc/src/v1/helpers/dispatch/full.rs @@ -118,7 +118,7 @@ impl Dispatcher fn sign

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

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

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

{ pub fn new( - signer: Arc, + signer: Arc, filled: FilledTransactionRequest, chain_id: Option, reserved: nonce::Reserved, diff --git a/rpc/src/v1/helpers/external_signer/mod.rs b/rpc/src/v1/helpers/external_signer/mod.rs index 0797929cbdf..05796c30a0e 100644 --- a/rpc/src/v1/helpers/external_signer/mod.rs +++ b/rpc/src/v1/helpers/external_signer/mod.rs @@ -30,7 +30,7 @@ pub use self::signing_queue::QueueEvent; pub struct SignerService { is_enabled: bool, queue: Arc, - generate_new_token: Box Result + Send + Sync + 'static>, + generate_new_token: Box Result + Send + Sync + 'static>, } impl SignerService { diff --git a/rpc/src/v1/helpers/external_signer/signing_queue.rs b/rpc/src/v1/helpers/external_signer/signing_queue.rs index 6f3435076f7..2eb5b712911 100644 --- a/rpc/src/v1/helpers/external_signer/signing_queue.rs +++ b/rpc/src/v1/helpers/external_signer/signing_queue.rs @@ -96,7 +96,7 @@ pub type ConfirmationReceiver = oneshot::Receiver; pub struct ConfirmationsQueue { id: Mutex, queue: RwLock>, - on_event: RwLock () + Send + Sync>>>, + on_event: RwLock () + Send + Sync>>>, } impl ConfirmationsQueue { diff --git a/rpc/src/v1/helpers/light_fetch.rs b/rpc/src/v1/helpers/light_fetch.rs index f2e67f86c9d..7e97add0aad 100644 --- a/rpc/src/v1/helpers/light_fetch.rs +++ b/rpc/src/v1/helpers/light_fetch.rs @@ -82,7 +82,7 @@ where OD: OnDemandRequester + 'static { /// The light client. - pub client: Arc, + pub client: Arc, /// The on-demand request service. pub on_demand: Arc, /// Handle to the network. @@ -585,7 +585,7 @@ where match maybe_future { Some(recv) => recv, - None => Box::new(future::err(errors::network_disabled())) as Box + Send> + None => Box::new(future::err(errors::network_disabled())) as Box + Send> } } @@ -741,7 +741,7 @@ where tx: EthTransaction, hdr: encoded::Header, env_info: ::vm::EnvInfo, - engine: Arc, + engine: Arc, on_demand: Arc, sync: Arc, } @@ -806,7 +806,7 @@ where failed => Ok(future::Loop::Break(failed)), } }) - })) as Box + Send> + })) as Box + Send> } else { trace!(target: "light_fetch", "Placing execution request for {} gas in on_demand", params.tx.gas); @@ -827,8 +827,8 @@ where }); match proved_future { - Some(fut) => Box::new(fut) as Box + Send>, - None => Box::new(future::err(errors::network_disabled())) as Box + Send>, + Some(fut) => Box::new(fut) as Box + Send>, + None => Box::new(future::err(errors::network_disabled())) as Box + Send>, } } } diff --git a/rpc/src/v1/helpers/subscription_manager.rs b/rpc/src/v1/helpers/subscription_manager.rs index 8323060b781..b2dacba882b 100644 --- a/rpc/src/v1/helpers/subscription_manager.rs +++ b/rpc/src/v1/helpers/subscription_manager.rs @@ -87,7 +87,7 @@ impl> GenericPollManager { }).is_some() } - pub fn tick(&self) -> Box + Send> { + pub fn tick(&self) -> Box + Send> { let mut futures = Vec::new(); // poll all subscriptions for (id, subscription) in self.subscribers.iter() { diff --git a/rpc/src/v1/impls/eth.rs b/rpc/src/v1/impls/eth.rs index 50237326aa6..5c572b8ee48 100644 --- a/rpc/src/v1/impls/eth.rs +++ b/rpc/src/v1/impls/eth.rs @@ -113,7 +113,7 @@ pub struct EthClient where client: Arc, snapshot: Arc, sync: Arc, - accounts: Arc Vec

+ Send + Sync>, + accounts: Arc Vec
+ Send + Sync>, miner: Arc, external_miner: Arc, seed_compute: Mutex, @@ -193,7 +193,7 @@ impl EthClient, snapshot: &Arc, sync: &Arc, - accounts: &Arc Vec
+ Send + Sync>, + accounts: &Arc Vec
+ Send + Sync>, miner: &Arc, em: &Arc, options: EthClientOptions @@ -449,8 +449,8 @@ impl EthClient) - .unwrap_or(Box::new(self.client.latest_state()) as Box) + .map(|s| Box::new(s) as Box) + .unwrap_or(Box::new(self.client.latest_state()) as Box) .into() } } diff --git a/rpc/src/v1/impls/eth_pubsub.rs b/rpc/src/v1/impls/eth_pubsub.rs index d9fe2329e91..7841827e934 100644 --- a/rpc/src/v1/impls/eth_pubsub.rs +++ b/rpc/src/v1/impls/eth_pubsub.rs @@ -137,7 +137,7 @@ where { /// Creates a new `EthPubSubClient` for `LightClient`. pub fn light( - client: Arc, + client: Arc, on_demand: Arc, sync: Arc, cache: Arc>, diff --git a/rpc/src/v1/impls/light/eth.rs b/rpc/src/v1/impls/light/eth.rs index 6467bfbc78b..3f94a0aa6d1 100644 --- a/rpc/src/v1/impls/light/eth.rs +++ b/rpc/src/v1/impls/light/eth.rs @@ -58,7 +58,7 @@ pub struct EthClient, on_demand: Arc, transaction_queue: Arc>, - accounts: Arc Vec
+ Send + Sync>, + accounts: Arc Vec
+ Send + Sync>, cache: Arc>, polls: Mutex>, poll_lifetime: u32, @@ -101,7 +101,7 @@ where client: Arc, on_demand: Arc, transaction_queue: Arc>, - accounts: Arc Vec
+ Send + Sync>, + accounts: Arc Vec
+ Send + Sync>, cache: Arc>, gas_price_percentile: usize, poll_lifetime: u32 diff --git a/rpc/src/v1/impls/light/parity_set.rs b/rpc/src/v1/impls/light/parity_set.rs index 68fc212b2fb..8195e4ddaf3 100644 --- a/rpc/src/v1/impls/light/parity_set.rs +++ b/rpc/src/v1/impls/light/parity_set.rs @@ -34,14 +34,14 @@ use v1::types::{Bytes, ReleaseInfo, Transaction}; /// Parity-specific rpc interface for operations altering the settings. pub struct ParitySetClient { - client: Arc, - net: Arc, + client: Arc, + net: Arc, fetch: F, } impl ParitySetClient { /// Creates new `ParitySetClient` with given `Fetch`. - pub fn new(client: Arc, net: Arc, fetch: F) -> Self { + pub fn new(client: Arc, net: Arc, fetch: F) -> Self { ParitySetClient { client, net, diff --git a/rpc/src/v1/impls/parity.rs b/rpc/src/v1/impls/parity.rs index 0dd6572130c..3503af586b1 100644 --- a/rpc/src/v1/impls/parity.rs +++ b/rpc/src/v1/impls/parity.rs @@ -59,13 +59,13 @@ pub struct ParityClient { client: Arc, miner: Arc, updater: Arc, - sync: Arc, - net: Arc, + sync: Arc, + net: Arc, logger: Arc, settings: Arc, signer: Option>, ws_address: Option, - snapshot: Option>, + snapshot: Option>, } impl ParityClient where @@ -75,14 +75,14 @@ impl ParityClient where pub fn new( client: Arc, miner: Arc, - sync: Arc, + sync: Arc, updater: Arc, - net: Arc, + net: Arc, logger: Arc, settings: Arc, signer: Option>, ws_address: Option, - snapshot: Option>, + snapshot: Option>, ) -> Self { ParityClient { client, diff --git a/rpc/src/v1/impls/parity_set.rs b/rpc/src/v1/impls/parity_set.rs index 25d06ed8514..7d7b46847af 100644 --- a/rpc/src/v1/impls/parity_set.rs +++ b/rpc/src/v1/impls/parity_set.rs @@ -87,7 +87,7 @@ pub struct ParitySetClient { client: Arc, miner: Arc, updater: Arc, - net: Arc, + net: Arc, fetch: F, } @@ -99,7 +99,7 @@ impl ParitySetClient client: &Arc, miner: &Arc, updater: &Arc, - net: &Arc, + net: &Arc, fetch: F, ) -> Self { ParitySetClient { diff --git a/rpc/src/v1/impls/signer.rs b/rpc/src/v1/impls/signer.rs index 3672f3c4c66..b135a1fbaa4 100644 --- a/rpc/src/v1/impls/signer.rs +++ b/rpc/src/v1/impls/signer.rs @@ -40,7 +40,7 @@ use v1::types::{TransactionModification, ConfirmationRequest, ConfirmationRespon /// Transactions confirmation (personal) rpc implementation. pub struct SignerClient { signer: Arc, - accounts: Arc, + accounts: Arc, dispatcher: D, subscribers: Arc>>>>, deprecation_notice: DeprecationNotice, @@ -49,7 +49,7 @@ pub struct SignerClient { impl SignerClient { /// Create new instance of signer client. pub fn new( - accounts: Arc, + accounts: Arc, dispatcher: D, signer: &Arc, executor: Executor, @@ -81,7 +81,7 @@ impl SignerClient { } fn confirm_internal(&self, id: U256, modification: TransactionModification, f: F) -> BoxFuture> where - F: FnOnce(D, &Arc, ConfirmationPayload) -> T, + F: FnOnce(D, &Arc, ConfirmationPayload) -> T, T: IntoFuture, Error=Error>, T::Future: Send + 'static { diff --git a/rpc/src/v1/impls/signing.rs b/rpc/src/v1/impls/signing.rs index 38ca6d59c9c..dc44e5bd437 100644 --- a/rpc/src/v1/impls/signing.rs +++ b/rpc/src/v1/impls/signing.rs @@ -91,7 +91,7 @@ fn schedule(executor: Executor, /// Implementation of functions that require signing when no trusted signer is used. pub struct SigningQueueClient { signer: Arc, - accounts: Arc, + accounts: Arc, dispatcher: D, executor: Executor, // None here means that the request hasn't yet been confirmed @@ -101,7 +101,7 @@ pub struct SigningQueueClient { impl SigningQueueClient { /// Creates a new signing queue client given shared signing queue. - pub fn new(signer: &Arc, dispatcher: D, executor: Executor, accounts: &Arc) -> Self { + pub fn new(signer: &Arc, dispatcher: D, executor: Executor, accounts: &Arc) -> Self { SigningQueueClient { signer: signer.clone(), accounts: accounts.clone(), diff --git a/rpc/src/v1/impls/signing_unsafe.rs b/rpc/src/v1/impls/signing_unsafe.rs index f08a9ffbe6e..4916e592f6a 100644 --- a/rpc/src/v1/impls/signing_unsafe.rs +++ b/rpc/src/v1/impls/signing_unsafe.rs @@ -37,14 +37,14 @@ use v1::types::{ /// Implementation of functions that require signing when no trusted signer is used. pub struct SigningUnsafeClient { - accounts: Arc, + accounts: Arc, dispatcher: D, deprecation_notice: DeprecationNotice, } impl SigningUnsafeClient { /// Creates new SigningUnsafeClient. - pub fn new(accounts: &Arc, dispatcher: D) -> Self { + pub fn new(accounts: &Arc, dispatcher: D) -> Self { SigningUnsafeClient { accounts: accounts.clone(), dispatcher, diff --git a/rpc/src/v1/tests/helpers/miner_service.rs b/rpc/src/v1/tests/helpers/miner_service.rs index 8bff84dc3b2..48c7829b940 100644 --- a/rpc/src/v1/tests/helpers/miner_service.rs +++ b/rpc/src/v1/tests/helpers/miner_service.rs @@ -55,7 +55,7 @@ pub struct TestMinerService { /// Minimum gas price pub min_gas_price: RwLock>, /// Signer (if any) - pub signer: RwLock>>, + pub signer: RwLock>>, authoring_params: RwLock, } @@ -102,7 +102,7 @@ impl StateClient for TestMinerService { } impl EngineInfo for TestMinerService { - fn engine(&self) -> &Engine { + fn engine(&self) -> &dyn Engine { unimplemented!() } } diff --git a/rpc/src/v1/tests/mocked/manage_network.rs b/rpc/src/v1/tests/mocked/manage_network.rs index d327a8743c6..abb2bc96351 100644 --- a/rpc/src/v1/tests/mocked/manage_network.rs +++ b/rpc/src/v1/tests/mocked/manage_network.rs @@ -31,5 +31,5 @@ impl ManageNetwork for TestManageNetwork { fn start_network(&self) {} fn stop_network(&self) {} fn num_peers_range(&self) -> RangeInclusive { 25..=50 } - fn with_proto_context(&self, _: ProtocolId, _: &mut FnMut(&NetworkContext)) { } + fn with_proto_context(&self, _: ProtocolId, _: &mut dyn FnMut(&dyn NetworkContext)) { } } diff --git a/rpc/src/v1/tests/mocked/parity.rs b/rpc/src/v1/tests/mocked/parity.rs index e8a83bb355d..7914ac4ed77 100644 --- a/rpc/src/v1/tests/mocked/parity.rs +++ b/rpc/src/v1/tests/mocked/parity.rs @@ -45,7 +45,7 @@ pub struct Dependencies { pub updater: Arc, pub logger: Arc, pub settings: Arc, - pub network: Arc, + pub network: Arc, pub ws_address: Option, } diff --git a/rpc/src/v1/tests/mocked/parity_set.rs b/rpc/src/v1/tests/mocked/parity_set.rs index 683f681e444..1ae42c69125 100644 --- a/rpc/src/v1/tests/mocked/parity_set.rs +++ b/rpc/src/v1/tests/mocked/parity_set.rs @@ -58,7 +58,7 @@ fn parity_set_client( client, miner, updater, - &(net.clone() as Arc), + &(net.clone() as Arc), FakeFetch::new(Some(1)), ) } diff --git a/rpc/src/v1/types/derivation.rs b/rpc/src/v1/types/derivation.rs index 1f2764d9ff2..907ce3a0048 100644 --- a/rpc/src/v1/types/derivation.rs +++ b/rpc/src/v1/types/derivation.rs @@ -19,7 +19,7 @@ use serde::{Deserialize, Deserializer}; use serde::de::{Error, Visitor}; use ethereum_types::H256; -use ethstore; + /// Type of derivation pub enum DerivationType { diff --git a/updater/hash-fetch/src/client.rs b/updater/hash-fetch/src/client.rs index a3ebdce2688..ea50b08adb6 100644 --- a/updater/hash-fetch/src/client.rs +++ b/updater/hash-fetch/src/client.rs @@ -37,7 +37,7 @@ pub trait HashFetch: Send + Sync + 'static { /// 2. `on_done` - callback function invoked when the content is ready (or there was error during fetch) /// /// This function may fail immediately when fetch cannot be initialized or content cannot be resolved. - fn fetch(&self, hash: H256, abort: fetch::Abort, on_done: Box) + Send>); + fn fetch(&self, hash: H256, abort: fetch::Abort, on_done: Box) + Send>); } /// Hash-fetching error. @@ -111,12 +111,12 @@ pub struct Client { contract: URLHintContract, fetch: F, executor: Executor, - random_path: Arc PathBuf + Sync + Send>, + random_path: Arc PathBuf + Sync + Send>, } impl Client { /// Creates new instance of the `Client` given on-chain contract client, fetch service and task runner. - pub fn with_fetch(contract: Arc>, fetch: F, executor: Executor) -> Self { + pub fn with_fetch(contract: Arc>, fetch: F, executor: Executor) -> Self { Client { contract: URLHintContract::new(contract), fetch: fetch, @@ -127,7 +127,7 @@ impl Client { } impl HashFetch for Client { - fn fetch(&self, hash: H256, abort: fetch::Abort, on_done: Box) + Send>) { + fn fetch(&self, hash: H256, abort: fetch::Abort, on_done: Box) + Send>) { debug!(target: "fetch", "Fetching: {:?}", hash); let random_path = self.random_path.clone(); diff --git a/updater/hash-fetch/src/lib.rs b/updater/hash-fetch/src/lib.rs index a9ddc7363e3..1d3b9e105bd 100644 --- a/updater/hash-fetch/src/lib.rs +++ b/updater/hash-fetch/src/lib.rs @@ -35,7 +35,7 @@ extern crate registrar; pub extern crate fetch; -#[macro_use] +// #[macro_use] extern crate ethabi_derive; #[macro_use] extern crate ethabi_contract; diff --git a/updater/hash-fetch/src/urlhint.rs b/updater/hash-fetch/src/urlhint.rs index 59829d1daf3..27af8238b37 100644 --- a/updater/hash-fetch/src/urlhint.rs +++ b/updater/hash-fetch/src/urlhint.rs @@ -95,18 +95,18 @@ pub enum URLHintResult { /// URLHint Contract interface pub trait URLHint: Send + Sync { /// Resolves given id to registrar entry. - fn resolve(&self, id: H256) -> Box, Error = String> + Send>; + fn resolve(&self, id: H256) -> Box, Error = String> + Send>; } /// `URLHintContract` API pub struct URLHintContract { registrar: Registrar, - client: Arc>, + client: Arc>, } impl URLHintContract { /// Creates new `URLHintContract` - pub fn new(client: Arc>) -> Self { + pub fn new(client: Arc>) -> Self { URLHintContract { registrar: Registrar::new(client.clone()), client: client, @@ -159,7 +159,7 @@ fn decode_urlhint_output(output: (String, [u8; 20], Address)) -> Option Box, Error = String> + Send> { + fn resolve(&self, id: H256) -> Box, Error = String> + Send> { let client = self.client.clone(); let future = self.registrar.get_address(GITHUB_HINT) diff --git a/updater/src/lib.rs b/updater/src/lib.rs index 7bc4eab7df9..1abfe2cb621 100644 --- a/updater/src/lib.rs +++ b/updater/src/lib.rs @@ -21,6 +21,7 @@ extern crate client_traits; extern crate common_types; extern crate ethabi; +extern crate ethabi_derive; extern crate ethcore; extern crate ethcore_sync as sync; extern crate ethereum_types; @@ -37,8 +38,6 @@ extern crate target_info; #[macro_use] extern crate ethabi_contract; #[macro_use] -extern crate ethabi_derive; -#[macro_use] extern crate lazy_static; #[macro_use] extern crate log; diff --git a/updater/src/updater.rs b/updater/src/updater.rs index ec51ffd9aa0..c675fef9417 100644 --- a/updater/src/updater.rs +++ b/updater/src/updater.rs @@ -144,11 +144,11 @@ pub struct Updater>>, - client: Weak, - sync: Option>, + client: Weak, + sync: Option>, fetcher: F, operations_client: O, - exit_handler: Mutex>>, + exit_handler: Mutex>>, time_provider: T, rng: R, @@ -205,11 +205,11 @@ pub trait OperationsClient: Send + Sync + 'static { /// `OperationsClient` that delegates calls to the operations contract. pub struct OperationsContractClient { - client: Weak, + client: Weak, } impl OperationsContractClient { - fn new(client: Weak) -> Self { + fn new(client: Weak) -> Self { OperationsContractClient { client } @@ -368,8 +368,8 @@ impl GenRange for ThreadRngGenRange { impl Updater { /// `Updater` constructor pub fn new( - client: &Weak, - sync: &Weak, + client: &Weak, + sync: &Weak, update_policy: UpdatePolicy, fetcher: fetch::Client, ) -> Arc { @@ -756,7 +756,7 @@ pub mod tests { #[derive(Clone)] struct FakeFetch { - on_done: Arc) + Send>>>>, + on_done: Arc) + Send>>>>, } impl FakeFetch { @@ -772,7 +772,7 @@ pub mod tests { } impl HashFetch for FakeFetch { - fn fetch(&self, _hash: H256, _abort: fetch::Abort, on_done: Box) + Send>) { + fn fetch(&self, _hash: H256, _abort: fetch::Abort, on_done: Box) + Send>) { *self.on_done.lock() = Some(on_done); } } diff --git a/util/EIP-712/src/error.rs b/util/EIP-712/src/error.rs index 3ec1292bb56..0eaa8e7bd0f 100644 --- a/util/EIP-712/src/error.rs +++ b/util/EIP-712/src/error.rs @@ -67,7 +67,7 @@ pub(crate) fn serde_error(expected: &str, field: Option<&str>) -> ErrorKind { } impl Fail for Error { - fn cause(&self) -> Option<&Fail> { + fn cause(&self) -> Option<&dyn Fail> { self.inner.cause() } diff --git a/util/fetch/src/client.rs b/util/fetch/src/client.rs index e4474fb7939..696b624ef56 100644 --- a/util/fetch/src/client.rs +++ b/util/fetch/src/client.rs @@ -271,7 +271,7 @@ impl Client { } impl Fetch for Client { - type Result = Box + Send + 'static>; + type Result = Box + Send + 'static>; fn fetch(&self, request: Request, abort: Abort) -> Self::Result { debug!(target: "fetch", "fetching: {:?}", request.url()); @@ -608,7 +608,7 @@ impl fmt::Display for Error { impl ::std::error::Error for Error { fn description(&self) -> &str { "Fetch client error" } - fn cause(&self) -> Option<&::std::error::Error> { None } + fn cause(&self) -> Option<&dyn std::error::Error> { None } } impl From for Error { diff --git a/util/migration-rocksdb/src/lib.rs b/util/migration-rocksdb/src/lib.rs index d63f2843ca3..4085d20bc11 100644 --- a/util/migration-rocksdb/src/lib.rs +++ b/util/migration-rocksdb/src/lib.rs @@ -32,7 +32,7 @@ use std::{fs, io, error}; use kvdb::DBTransaction; use kvdb_rocksdb::{CompactionProfile, Database, DatabaseConfig}; -fn other_io_err(e: E) -> io::Error where E: Into> { +fn other_io_err(e: E) -> io::Error where E: Into> { io::Error::new(io::ErrorKind::Other, e) } @@ -209,7 +209,7 @@ impl TempIndex { /// Manages database migration. pub struct Manager { config: Config, - migrations: Vec>, + migrations: Vec>, } impl Manager { @@ -317,7 +317,7 @@ impl Manager { } /// Find all needed migrations. - fn migrations_from(&mut self, version: u32) -> Vec<&mut Box> { + fn migrations_from(&mut self, version: u32) -> Vec<&mut Box> { self.migrations.iter_mut().filter(|m| m.version() > version).collect() } } diff --git a/util/network-devp2p/src/ip_utils.rs b/util/network-devp2p/src/ip_utils.rs index 63f440b498f..0a599155d32 100644 --- a/util/network-devp2p/src/ip_utils.rs +++ b/util/network-devp2p/src/ip_utils.rs @@ -97,12 +97,12 @@ impl SocketAddrExt for Ipv4Addr { self.is_multicast() || self.is_shared_space() || self.is_special_purpose() || - self.is_benchmarking() || + SocketAddrExt::is_benchmarking(self) || self.is_future_use() } fn is_usable_public(&self) -> bool { - !self.is_reserved() && + !SocketAddrExt::is_reserved(self) && !self.is_private() } @@ -186,7 +186,7 @@ impl SocketAddrExt for IpAddr { fn is_reserved(&self) -> bool { match *self { - IpAddr::V4(ref ip) => ip.is_reserved(), + IpAddr::V4(ref ip) => SocketAddrExt::is_reserved(ip), IpAddr::V6(ref ip) => ip.is_reserved(), } } @@ -290,7 +290,7 @@ pub fn select_public_address(port: u16) -> SocketAddr { //prefer IPV4 bindings for addr in &list { //TODO: use better criteria than just the first in the list match addr { - IpAddr::V4(a) if !a.is_reserved() => { + IpAddr::V4(a) if !SocketAddrExt::is_reserved(a) => { return SocketAddr::V4(SocketAddrV4::new(*a, port)); }, _ => {}, diff --git a/util/network/src/error.rs b/util/network/src/error.rs index 81e3b78b887..c43de6b8d58 100644 --- a/util/network/src/error.rs +++ b/util/network/src/error.rs @@ -145,7 +145,7 @@ impl From> for AddressResolveError { } impl error::Error for Error { - fn source(&self) -> Option<&(error::Error + 'static)> { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self { Error::Decompression(e) => Some(e), Error::Rlp(e) => Some(e), diff --git a/util/network/src/lib.rs b/util/network/src/lib.rs index be47fa36755..31071655c65 100644 --- a/util/network/src/lib.rs +++ b/util/network/src/lib.rs @@ -75,7 +75,7 @@ pub enum NetworkIoMessage { /// Register a new protocol handler. AddHandler { /// Handler shared instance. - handler: Arc, + handler: Arc, /// Protocol Id. protocol: ProtocolId, /// Supported protocol versions and number of packet IDs reserved by the protocol (packet count). @@ -361,15 +361,15 @@ impl<'a, T> NetworkContext for &'a T where T: ?Sized + NetworkContext { /// `Message` is the type for message data. pub trait NetworkProtocolHandler: Sync + Send { /// Initialize the handler - fn initialize(&self, _io: &NetworkContext) {} + fn initialize(&self, _io: &dyn NetworkContext) {} /// Called when new network packet received. - fn read(&self, io: &NetworkContext, peer: &PeerId, packet_id: u8, data: &[u8]); + fn read(&self, io: &dyn NetworkContext, peer: &PeerId, packet_id: u8, data: &[u8]); /// Called when new peer is connected. Only called when peer supports the same protocol. - fn connected(&self, io: &NetworkContext, peer: &PeerId); + fn connected(&self, io: &dyn NetworkContext, peer: &PeerId); /// Called when a previously connected peer disconnects. - fn disconnected(&self, io: &NetworkContext, peer: &PeerId); + fn disconnected(&self, io: &dyn NetworkContext, peer: &PeerId); /// Timer function called after a timeout created with `NetworkContext::timeout`. - fn timeout(&self, _io: &NetworkContext, _timer: TimerToken) {} + fn timeout(&self, _io: &dyn NetworkContext, _timer: TimerToken) {} } /// Non-reserved peer modes. diff --git a/util/registrar/src/lib.rs b/util/registrar/src/lib.rs index d07e17c1bc1..40a7de90376 100644 --- a/util/registrar/src/lib.rs +++ b/util/registrar/src/lib.rs @@ -16,10 +16,9 @@ extern crate futures; extern crate ethabi; +extern crate ethabi_derive; extern crate keccak_hash; -#[macro_use] -extern crate ethabi_derive; #[macro_use] extern crate ethabi_contract; diff --git a/util/registrar/src/registrar.rs b/util/registrar/src/registrar.rs index cd6d35660a8..bc7fe097649 100644 --- a/util/registrar/src/registrar.rs +++ b/util/registrar/src/registrar.rs @@ -24,25 +24,25 @@ use_contract!(registrar, "res/registrar.json"); // Maps a domain name to an Ethereum address const DNS_A_RECORD: &'static str = "A"; -pub type Asynchronous = Box + Send>; +pub type Asynchronous = Box + Send>; pub type Synchronous = Result; /// Registrar is dedicated interface to access the registrar contract /// which in turn generates an address when a client requests one pub struct Registrar { - client: Arc>, + client: Arc>, } impl Registrar { /// Registrar constructor - pub fn new(client: Arc>) -> Self { + pub fn new(client: Arc>) -> Self { Self { client: client, } } /// Generate an address for the given key - pub fn get_address<'a>(&self, key: &'a str) -> Box + Send> { + pub fn get_address<'a>(&self, key: &'a str) -> Box + Send> { // Address of the registrar itself let registrar_address = match self.client.registrar_address() { Ok(a) => a, diff --git a/util/rlp-compress/src/lib.rs b/util/rlp-compress/src/lib.rs index 48620ed239d..890cd66f871 100644 --- a/util/rlp-compress/src/lib.rs +++ b/util/rlp-compress/src/lib.rs @@ -40,7 +40,7 @@ pub trait Decompressor { } /// Call this function to compress rlp. -pub fn compress(c: &[u8], swapper: &Compressor) -> ElasticArray1024 { +pub fn compress(c: &[u8], swapper: &dyn Compressor) -> ElasticArray1024 { let rlp = Rlp::new(c); if rlp.is_data() { ElasticArray1024::from_slice(swapper.compressed(rlp.as_raw()).unwrap_or_else(|| rlp.as_raw())) @@ -50,7 +50,7 @@ pub fn compress(c: &[u8], swapper: &Compressor) -> ElasticArray1024 { } /// Call this function to decompress rlp. -pub fn decompress(c: &[u8], swapper: &Decompressor) -> ElasticArray1024 { +pub fn decompress(c: &[u8], swapper: &dyn Decompressor) -> ElasticArray1024 { let rlp = Rlp::new(c); if rlp.is_data() { ElasticArray1024::from_slice(swapper.decompressed(rlp.as_raw()).unwrap_or_else(|| rlp.as_raw())) From 974b24549b7aca58575f8a99848a551090fbd34a Mon Sep 17 00:00:00 2001 From: Niklas Adolfsson Date: Tue, 27 Aug 2019 23:59:39 +0200 Subject: [PATCH 2/7] bump spin to 0.5.2 (#10996) patch vulnerability https://github.com/RustSec/advisory-db/pull/132 --- Cargo.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d4867ad3362..73488c65ac3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3865,7 +3865,7 @@ dependencies = [ "cc 1.0.28 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.48 (registry+https://github.com/rust-lang/crates.io-index)", - "spin 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "spin 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)", "untrusted 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -4205,7 +4205,7 @@ dependencies = [ [[package]] name = "spin" -version = "0.5.0" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -5447,7 +5447,7 @@ dependencies = [ "checksum slab 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5f9776d6b986f77b35c6cf846c11ad986ff128fe0b2b63a3628e3755e8d3102d" "checksum smallvec 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)" = "ab606a9c5e214920bb66c458cd7be8ef094f813f20fe77a54cc7dbfff220d4b7" "checksum socket2 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "c4d11a52082057d87cb5caa31ad812f4504b97ab44732cd8359df2e9ff9f48e7" -"checksum spin 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "44363f6f51401c34e7be73db0db371c04705d35efbe9f7d6082e03a921a32c55" +"checksum spin 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" "checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8" "checksum static_assertions 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "c19be23126415861cb3a23e501d34a708f7f9b2183c5252d690941c2e69199d5" "checksum static_assertions 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "b4f8de36da215253eb5f24020bfaa0646613b48bf7ebe36cdfa37c3b3b33b241" From cd265268687374607ed9e6a1fe820731e9fc46bb Mon Sep 17 00:00:00 2001 From: David Date: Wed, 28 Aug 2019 10:09:42 +0200 Subject: [PATCH 3/7] Make ClientIoMessage generic over the Client (#10981) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add client-traits crate Move the BlockInfo trait to new crate * New crate `machine` Contains code extracted from ethcore that defines `Machine`, `Externalities` and other execution related code. * Use new machine and client-traits crates in ethcore * Use new crates machine and client-traits instead of ethcore where appropriate * Fix tests * Don't re-export so many types from ethcore::client * Fixing more fallout from removing re-export * fix test * More fallout from not re-exporting types * Add some docs * cleanup * import the macro edition style * Tweak docs * Add missing import * remove unused ethabi_derive imports * Use latest ethabi-contract * Move many traits from ethcore/client/traits to client-traits crate Initial version of extracted Engine trait * Move snapshot related traits to the engine crate (eew) * Move a few snapshot related types to common_types Cleanup Executed as exported from machine crate * fix warning * Gradually introduce new engine crate: snapshot * ethcore typechecks with new engine crate * Sort out types outside ethcore * Add an EpochVerifier to ethash and use that in Engine.epoch_verifier() Cleanup * Document pub members * Sort out tests Sort out default impls for EpochVerifier * Add test-helpers feature and move EngineSigner impl to the right place * Sort out tests * Sort out tests and refactor verification types * Fix missing traits * More missing traits Fix Histogram * Fix tests and cleanup * cleanup * Put back needed logger import * Don't rexport common_types from ethcore/src/client Don't export ethcore::client::* * Remove files no longer used Use types from the engine crate Explicit exports from engine::engine * Get rid of itertools * Move a few more traits from ethcore to client-traits: BlockChainReset, ScheduleInfo, StateClient * Move ProvingBlockChainClient to client-traits * Don't re-export ForkChoice and Transition from ethcore * Address grumbles: sort imports, remove commented out code * Fix merge resolution error * Extract the Clique engine to own crate * Extract NullEngine and the block_reward module from ethcore * Extract InstantSeal engine to own crate * Extract remaining engines * Extract executive_state to own crate so it can be used by engine crates * Remove snapshot stuff from the engine crate * Put snapshot traits back in ethcore * cleanup * Remove stuff from ethcore * Don't use itertools * itertools in aura is legit-ish * More post-merge fixes * Re-export less types in client * cleanup * Extract spec to own crate * Put back the test-helpers from basic-authority * Fix ethcore benchmarks * Reduce the public api of ethcore/verification * WIP * Add Cargo.toml * Fix compilation outside ethcore * Audit uses of import_verified_blocks() and remove unneeded calls Cleanup * cleanup * Remove unused imports from ethcore * Cleanup * remove double semi-colons * Add missing generic param * More missing generics * Update ethcore/block-reward/Cargo.toml Co-Authored-By: Tomasz Drwięga * Update ethcore/engines/basic-authority/Cargo.toml Co-Authored-By: Tomasz Drwięga * Update ethcore/engines/ethash/Cargo.toml Co-Authored-By: Tomasz Drwięga * Update ethcore/engines/clique/src/lib.rs Co-Authored-By: Tomasz Drwięga * signers is already a ref * Add an EngineType enum to tighten up Engine.name() * Introduce Snapshotting enum to distinguish the type of snapshots a chain uses * Rename supports_warp to snapshot_mode * Missing import * Update ethcore/src/snapshot/consensus/mod.rs Co-Authored-By: Tomasz Drwięga * missing import * Fix import * double semi * Fix merge problem * cleanup * Parametrise `ClientIoMessage` with `()` for the light client * Add impl Tick for () * Address review feedback * Move ClientIoMessage to common-types * remove superseeded fixme * fix merge conflict errors --- Cargo.lock | 37 ++- Cargo.toml | 1 + ethcore/Cargo.toml | 19 +- ethcore/client-traits/src/lib.rs | 55 ++++- ethcore/light/Cargo.toml | 2 +- ethcore/light/src/client/mod.rs | 11 +- ethcore/light/src/client/service.rs | 18 +- ethcore/light/src/lib.rs | 4 +- ethcore/private-tx/src/lib.rs | 15 +- ethcore/service/Cargo.toml | 1 + ethcore/service/src/lib.rs | 1 + ethcore/service/src/service.rs | 31 +-- ethcore/src/client/client.rs | 214 ++++++++---------- ethcore/src/client/mod.rs | 4 +- ethcore/src/client/test_client.rs | 4 + ethcore/src/json_tests/chain.rs | 1 - ethcore/src/lib.rs | 21 +- ethcore/src/miner/miner.rs | 36 ++- ethcore/src/miner/pool_client.rs | 52 ++--- ethcore/src/snapshot/io.rs | 15 +- ethcore/src/snapshot/mod.rs | 5 +- ethcore/src/snapshot/service.rs | 42 ++-- ethcore/src/snapshot/tests/helpers.rs | 2 +- ethcore/src/snapshot/tests/proof_of_work.rs | 3 +- ethcore/src/snapshot/tests/service.rs | 9 +- ethcore/src/snapshot/tests/state.rs | 3 +- ethcore/src/snapshot/watcher.rs | 11 +- ethcore/src/test_helpers.rs | 3 - ethcore/src/tests/client.rs | 7 +- ethcore/src/tests/trace.rs | 1 - ethcore/sync/src/tests/consensus.rs | 13 +- ethcore/sync/src/tests/helpers.rs | 7 +- ethcore/sync/src/tests/private.rs | 17 +- ethcore/types/src/client_types.rs | 42 ++++ .../{src/client => types/src}/io_message.rs | 18 +- ethcore/types/src/lib.rs | 1 + ethcore/verification/Cargo.toml | 34 +++ .../src}/canon_verifier.rs | 2 +- .../mod.rs => verification/src/lib.rs} | 7 +- .../src}/noop_verifier.rs | 4 +- .../src}/queue/kind.rs | 11 +- .../src}/queue/mod.rs | 94 ++++---- .../src}/verification.rs | 25 +- .../src}/verifier.rs | 5 +- parity/blockchain.rs | 4 +- parity/configuration.rs | 2 +- parity/informant.rs | 18 +- parity/lib.rs | 1 + parity/run.rs | 12 +- parity/snapshot.rs | 1 + rpc/Cargo.toml | 1 + rpc/src/lib.rs | 1 + rpc/src/v1/tests/eth.rs | 3 +- 53 files changed, 547 insertions(+), 404 deletions(-) rename ethcore/{src/client => types/src}/io_message.rs (78%) create mode 100644 ethcore/verification/Cargo.toml rename ethcore/{src/verification => verification/src}/canon_verifier.rs (98%) rename ethcore/{src/verification/mod.rs => verification/src/lib.rs} (95%) rename ethcore/{src/verification => verification/src}/noop_verifier.rs (98%) rename ethcore/{src/verification => verification/src}/queue/kind.rs (95%) rename ethcore/{src/verification => verification/src}/queue/mod.rs (93%) rename ethcore/{src/verification => verification/src}/verification.rs (98%) rename ethcore/{src/verification => verification/src}/verifier.rs (98%) diff --git a/Cargo.lock b/Cargo.lock index 73488c65ac3..8f866209af1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1052,7 +1052,6 @@ dependencies = [ "kvdb-memorydb 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "kvdb-rocksdb 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "len-caching-lock 0.1.1", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "machine 0.1.0", "macros 0.1.0", @@ -1062,7 +1061,6 @@ dependencies = [ "parity-bytes 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "parity-runtime 0.1.0", "parity-snappy 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-util-mem 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "patricia-trie-ethereum 0.1.0", "pod 0.1.0", @@ -1080,7 +1078,6 @@ dependencies = [ "state-db 0.1.0", "stats 0.1.0", "tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", - "time-utils 0.1.0", "trace 0.1.0", "trace-time 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "trie-db 0.15.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1089,6 +1086,7 @@ dependencies = [ "triehash-ethereum 0.2.0", "unexpected 0.1.0", "using_queue 0.1.0", + "verification 0.1.0", "vm 0.1.0", ] @@ -1245,6 +1243,7 @@ dependencies = [ "tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", "trie-db 0.15.0 (registry+https://github.com/rust-lang/crates.io-index)", "triehash-ethereum 0.2.0", + "verification 0.1.0", "vm 0.1.0", ] @@ -1451,6 +1450,7 @@ name = "ethcore-service" version = "0.1.0" dependencies = [ "ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", + "client-traits 0.1.0", "common-types 0.1.0", "ethcore 1.12.0", "ethcore-blockchain 0.1.0", @@ -3021,6 +3021,7 @@ dependencies = [ "term_size 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "textwrap 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "toml 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)", + "verification 0.1.0", "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -3171,6 +3172,7 @@ dependencies = [ "trace 0.1.0", "transaction-pool 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "transient-hashmap 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", + "verification 0.1.0", "vm 0.1.0", ] @@ -4947,6 +4949,35 @@ dependencies = [ "time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "verification" +version = "0.1.0" +dependencies = [ + "client-traits 0.1.0", + "common-types 0.1.0", + "engine 0.1.0", + "ethcore 1.12.0", + "ethcore-blockchain 0.1.0", + "ethcore-call-contract 0.1.0", + "ethcore-io 1.12.0", + "ethereum-types 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "ethkey 0.3.0", + "keccak-hash 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "len-caching-lock 0.1.1", + "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", + "machine 0.1.0", + "null-engine 0.1.0", + "num_cpus 1.10.1 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-bytes 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-util-mem 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rlp 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "spec 0.1.0", + "time-utils 0.1.0", + "triehash-ethereum 0.2.0", + "unexpected 0.1.0", +] + [[package]] name = "version_check" version = "0.1.5" diff --git a/Cargo.toml b/Cargo.toml index d8eb2179793..298c1542e8f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,6 +73,7 @@ spec = { path = "ethcore/spec" } term_size = "0.3" textwrap = "0.9" toml = "0.4" +verification = { path = "ethcore/verification" } [build-dependencies] rustc_version = "0.2" diff --git a/ethcore/Cargo.toml b/ethcore/Cargo.toml index d87133a502b..cf27c1a6585 100644 --- a/ethcore/Cargo.toml +++ b/ethcore/Cargo.toml @@ -35,16 +35,14 @@ evm = { path = "evm" } executive-state = { path = "executive-state" } futures = "0.1" hash-db = "0.15.0" -parity-util-mem = "0.2.0" itertools = "0.5" journaldb = { path = "../util/journaldb" } keccak-hash = "0.2.0" keccak-hasher = { path = "../util/keccak-hasher" } kvdb = "0.1" -kvdb-memorydb = "0.1" +kvdb-memorydb = { version = "0.1", optional = true } kvdb-rocksdb = { version = "0.1.3", optional = true } -lazy_static = "1.3.0" -len-caching-lock = { path = "../util/len-caching-lock" } +lazy_static = { version = "1.3", optional = true } log = "0.4" macros = { path = "../util/macros", optional = true } machine = { path = "./machine" } @@ -61,20 +59,19 @@ rand_xorshift = "0.1.1" rayon = "1.1" rlp = "0.4.0" rlp_derive = { path = "../util/rlp-derive" } -rustc-hex = "1.0" +rustc-hex = { version = "1", optional = true } serde = "1.0" serde_derive = "1.0" spec = { path = "spec" } state-db = { path = "state-db" } -stats = { path = "../util/stats" } tempdir = { version = "0.3", optional = true } -time-utils = { path = "../util/time-utils" } trace = { path = "trace" } trace-time = "0.1" trie-vm-factories = { path = "trie-vm-factories" } triehash-ethereum = { version = "0.2", path = "../util/triehash-ethereum" } unexpected = { path = "../util/unexpected" } using_queue = { path = "../miner/using-queue" } +verification = { path = "./verification" } vm = { path = "vm" } [dev-dependencies] @@ -88,14 +85,18 @@ ethcore-accounts = { path = "../accounts" } ethjson = { path = "../json" } ethkey = { path = "../accounts/ethkey" } fetch = { path = "../util/fetch" } +kvdb-memorydb = "0.1" kvdb-rocksdb = "0.1.3" +lazy_static = { version = "1.3" } machine = { path = "./machine", features = ["test-helpers"] } macros = { path = "../util/macros" } null-engine = { path = "./engines/null-engine" } parity-runtime = { path = "../util/runtime" } pod = { path = "pod" } rlp_compress = { path = "../util/rlp-compress" } +rustc-hex = "1" serde_json = "1.0" +stats = { path = "../util/stats" } tempdir = "0.3" trie-standardmap = "0.15.0" @@ -121,14 +122,14 @@ evm-debug-tests = ["evm-debug", "evm/evm-debug-tests"] # EVM debug traces are printed. slow-blocks = [] # Run JSON consensus tests. -json-tests = ["env_logger", "test-helpers", "machine/test-helpers"] +json-tests = ["env_logger", "test-helpers", "lazy_static", "machine/test-helpers"] # Skip JSON consensus tests with pending issues. ci-skip-tests = [] # Run memory/cpu heavy tests. test-heavy = [] # Compile test helpers # note[dvdplm]: "basic-authority/test-helpers" is needed so that `generate_dummy_client_with_spec` works -test-helpers = ["tempdir", "kvdb-rocksdb", "blooms-db", "ethash", "ethjson", "ethkey", "macros", "pod", "basic-authority/test-helpers"] +test-helpers = ["tempdir", "kvdb-memorydb", "kvdb-rocksdb", "blooms-db", "ethash", "ethjson", "ethkey", "macros", "pod", "rustc-hex", "basic-authority/test-helpers"] [[bench]] name = "builtin" diff --git a/ethcore/client-traits/src/lib.rs b/ethcore/client-traits/src/lib.rs index af68b9b3f6c..896f9515b8b 100644 --- a/ethcore/client-traits/src/lib.rs +++ b/ethcore/client-traits/src/lib.rs @@ -32,7 +32,7 @@ use common_types::{ client_types::Mode, encoded, engines::{epoch::Transition as EpochTransition, machine::Executed}, - errors::EthcoreResult, + errors::{EthcoreError, EthcoreResult}, filter::Filter, header::Header, ids::{BlockId, TransactionId, TraceId, UncleId}, @@ -56,6 +56,8 @@ use trace::{ }; use vm::{LastHashes, Schedule}; +use common_types::snapshot::Progress; + /// State information to be used during client query pub enum StateOrBlock { /// State to be used, may be pending @@ -168,11 +170,14 @@ pub trait EngineClient: Sync + Send + ChainInfo { fn block_header(&self, id: BlockId) -> Option; } -// FIXME Why these methods belong to BlockChainClient and not MiningBlockChainClient? /// Provides methods to import block into blockchain pub trait ImportBlock { /// Import a block into the blockchain. fn import_block(&self, block: Unverified) -> EthcoreResult; + + /// Triggered by a message from a block queue when the block is ready for insertion. + /// Returns the number of blocks imported. + fn import_verified_blocks(&self) -> usize; } /// IO operations that should off-load heavy work to another thread. @@ -187,6 +192,14 @@ pub trait IoClient: Sync + Send { fn queue_consensus_message(&self, message: Bytes); } +/// Implement this for clients that need logic to decide when/how to advance. +pub trait Tick { + /// Tick the client + fn tick(&self, _prevent_sleep: bool) {} +} + +impl Tick for () {} + /// Provides recently seen bad blocks. pub trait BadBlocks { /// Returns a list of blocks that were recently not imported because they were invalid. @@ -377,6 +390,9 @@ pub trait BlockChainClient : Sync + Send + AccountData + BlockChain + CallContra pub trait BlockChainReset { /// reset to best_block - n fn reset(&self, num: u32) -> Result<(), String>; + + /// Number of eras kept in a journal before they are pruned + fn pruning_history(&self) -> u64; } @@ -423,3 +439,38 @@ pub trait ProvingBlockChainClient: BlockChainClient { /// Get an epoch change signal by block hash. fn epoch_signal(&self, hash: H256) -> Option>; } + +/// External database restoration handler +pub trait DatabaseRestore: Send + Sync { + /// Restart with a new backend. Takes ownership of passed database and moves it to a new location. + fn restore_db(&self, new_db: &str) -> Result<(), EthcoreError>; +} + +/// Snapshot related functionality +pub trait SnapshotClient: BlockChainClient + BlockInfo + DatabaseRestore + BlockChainReset { + /// Take a snapshot at the given block. + /// If the ID given is "latest", this will default to 1000 blocks behind. + fn take_snapshot( + &self, + writer: W, + at: BlockId, + p: &Progress, + ) -> Result<(), EthcoreError>; +} + + +// todo[dvdplm] move this back to snapshot once extracted from ethcore +/// Something which can write snapshots. +/// Writing the same chunk multiple times will lead to implementation-defined +/// behavior, and is not advised. +pub trait SnapshotWriter { + /// Write a compressed state chunk. + fn write_state_chunk(&mut self, hash: H256, chunk: &[u8]) -> std::io::Result<()>; + + /// Write a compressed block chunk. + fn write_block_chunk(&mut self, hash: H256, chunk: &[u8]) -> std::io::Result<()>; + + /// Complete writing. The manifest's chunk lists must be consistent + /// with the chunks written. + fn finish(self, manifest: common_types::snapshot::ManifestData) -> std::io::Result<()> where Self: Sized; +} diff --git a/ethcore/light/Cargo.toml b/ethcore/light/Cargo.toml index abc233744d1..32e0c5e00d0 100644 --- a/ethcore/light/Cargo.toml +++ b/ethcore/light/Cargo.toml @@ -13,7 +13,6 @@ client-traits = { path = "../client-traits" } common-types = { path = "../types" } derive_more = "0.14.0" engine = { path = "../engine" } -ethcore = { path = ".."} ethcore-db = { path = "../db" } ethcore-blockchain = { path = "../blockchain" } ethereum-types = "0.6.0" @@ -49,6 +48,7 @@ kvdb = "0.1" memory-cache = { path = "../../util/memory-cache" } error-chain = { version = "0.12", default-features = false } journaldb = { path = "../../util/journaldb" } +verification = { path = "../verification" } [dev-dependencies] ethcore = { path = "..", features = ["test-helpers"] } diff --git a/ethcore/light/src/client/mod.rs b/ethcore/light/src/client/mod.rs index 98149ea2f8b..0339cfe1b10 100644 --- a/ethcore/light/src/client/mod.rs +++ b/ethcore/light/src/client/mod.rs @@ -19,8 +19,7 @@ use std::sync::{Weak, Arc}; use engine::{Engine, EpochChange, Proof}; -use ethcore::client::{ClientReport, ClientIoMessage}; -use ethcore::verification::queue::{self, HeaderQueue}; +use verification::queue::{self, HeaderQueue}; use spec::{Spec, SpecHardcodedSync}; use io::IoChannel; use parking_lot::{Mutex, RwLock}; @@ -30,12 +29,14 @@ use common_types::{ BlockNumber, block_status::BlockStatus, blockchain_info::BlockChainInfo, + client_types::ClientReport, encoded, engines::epoch::{Transition as EpochTransition, PendingTransition}, errors::EthcoreError as Error, errors::EthcoreResult, header::Header, ids::BlockId, + io_message::ClientIoMessage, verification::VerificationQueueInfo as BlockQueueInfo, }; use kvdb::KeyValueDB; @@ -162,7 +163,7 @@ impl AsLightClient for T { /// Light client implementation. pub struct Client { - queue: HeaderQueue, + queue: HeaderQueue<()>, engine: Arc, chain: HeaderChain, report: RwLock, @@ -183,7 +184,7 @@ impl Client { chain_col: Option, spec: &Spec, fetcher: T, - io_channel: IoChannel, + io_channel: IoChannel>, cache: Arc> ) -> Result { Ok(Self { @@ -649,3 +650,5 @@ impl client_traits::EngineClient for Client { Client::block_header(self, id) } } + +impl client_traits::Tick for Client {} diff --git a/ethcore/light/src/client/service.rs b/ethcore/light/src/client/service.rs index 2a55322b464..2b22a7c15bf 100644 --- a/ethcore/light/src/client/service.rs +++ b/ethcore/light/src/client/service.rs @@ -20,10 +20,12 @@ use std::fmt; use std::sync::Arc; -use common_types::errors::EthcoreError as CoreError; +use common_types::{ + errors::EthcoreError as CoreError, + io_message::ClientIoMessage, +}; use ethcore_db as db; use ethcore_blockchain::BlockChainDB; -use ethcore::client::ClientIoMessage; use spec::Spec; use io::{IoContext, IoError, IoHandler, IoService}; @@ -58,15 +60,15 @@ impl fmt::Display for Error { } /// Light client service. -pub struct Service { +pub struct Service { client: Arc>, - io_service: IoService, + io_service: IoService>, } impl Service { /// Start the service: initialize I/O workers and client itself. pub fn start(config: ClientConfig, spec: &Spec, fetcher: T, db: Arc, cache: Arc>) -> Result { - let io_service = IoService::::start().map_err(Error::Io)?; + let io_service = IoService::>::start().map_err(Error::Io)?; let client = Arc::new(Client::new(config, db.key_value().clone(), db::COL_LIGHT_CHAIN, @@ -90,7 +92,7 @@ impl Service { } /// Register an I/O handler on the service. - pub fn register_handler(&self, handler: Arc + Send>) -> Result<(), IoError> { + pub fn register_handler(&self, handler: Arc> + Send>) -> Result<(), IoError> { self.io_service.register_handler(handler) } @@ -102,8 +104,8 @@ impl Service { struct ImportBlocks(Arc>); -impl IoHandler for ImportBlocks { - fn message(&self, _io: &IoContext, message: &ClientIoMessage) { +impl IoHandler> for ImportBlocks { + fn message(&self, _io: &IoContext>, message: &ClientIoMessage<()>) { if let ClientIoMessage::BlockVerified = *message { self.0.import_verified(); } diff --git a/ethcore/light/src/lib.rs b/ethcore/light/src/lib.rs index 3d2bd3752d7..61ce17e5632 100644 --- a/ethcore/light/src/lib.rs +++ b/ethcore/light/src/lib.rs @@ -65,7 +65,6 @@ extern crate executive_state; extern crate parity_bytes as bytes; extern crate ethereum_types; extern crate ethcore_miner as miner; -extern crate ethcore; extern crate hash_db; extern crate parity_util_mem; extern crate parity_util_mem as mem; @@ -94,7 +93,10 @@ extern crate triehash_ethereum as triehash; extern crate kvdb; extern crate memory_cache; extern crate derive_more; +extern crate verification; +#[cfg(test)] +extern crate ethcore; #[cfg(test)] extern crate kvdb_memorydb; #[cfg(test)] diff --git a/ethcore/private-tx/src/lib.rs b/ethcore/private-tx/src/lib.rs index 2368205baf8..8673d4be7c3 100644 --- a/ethcore/private-tx/src/lib.rs +++ b/ethcore/private-tx/src/lib.rs @@ -104,11 +104,12 @@ use machine::{ }; use types::{ ids::BlockId, + io_message::ClientIoMessage, transaction::{SignedTransaction, Transaction, Action, UnverifiedTransaction}, engines::machine::Executed, }; use ethcore::client::{ - Client, ChainNotify, NewBlocks, ChainMessageType, ClientIoMessage, Call + Client, ChainNotify, NewBlocks, ChainMessageType, Call }; use client_traits::BlockInfo; use ethcore::miner::{self, Miner, MinerService, pool_client::NonceCache}; @@ -213,7 +214,7 @@ pub struct Provider { client: Arc, miner: Arc, accounts: Arc, - channel: IoChannel, + channel: IoChannel>, keys_provider: Arc, logging: Option, use_offchain_storage: bool, @@ -236,7 +237,7 @@ impl Provider { accounts: Arc, encryptor: Box, config: ProviderConfig, - channel: IoChannel, + channel: IoChannel>, keys_provider: Arc, db: Arc, ) -> Self { @@ -490,7 +491,7 @@ impl Provider { } } Ok(()) - } + } fn contract_address_from_transaction(transaction: &SignedTransaction) -> Result { match transaction.action { @@ -876,14 +877,14 @@ impl Provider { } } -impl IoHandler for Provider { - fn initialize(&self, io: &IoContext) { +impl IoHandler> for Provider { + fn initialize(&self, io: &IoContext>) { if self.use_offchain_storage { io.register_timer(STATE_RETRIEVAL_TIMER, STATE_RETRIEVAL_TICK).expect("Error registering state retrieval timer"); } } - fn timeout(&self, _io: &IoContext, timer: TimerToken) { + fn timeout(&self, _io: &IoContext>, timer: TimerToken) { match timer { STATE_RETRIEVAL_TIMER => self.state_storage.tick(&self.logging), _ => warn!("IO service triggered unregistered timer '{}'", timer), diff --git a/ethcore/service/Cargo.toml b/ethcore/service/Cargo.toml index 6ab4afecd7a..f333e979d06 100644 --- a/ethcore/service/Cargo.toml +++ b/ethcore/service/Cargo.toml @@ -7,6 +7,7 @@ authors = ["Parity Technologies "] [dependencies] ansi_term = "0.11" common-types = { path = "../types" } +client-traits = { path = "../client-traits" } ethcore = { path = ".." } ethcore-blockchain = { path = "../blockchain" } ethcore-io = { path = "../../util/io" } diff --git a/ethcore/service/src/lib.rs b/ethcore/service/src/lib.rs index d49a3d30d39..662a2567669 100644 --- a/ethcore/service/src/lib.rs +++ b/ethcore/service/src/lib.rs @@ -16,6 +16,7 @@ extern crate ansi_term; extern crate common_types; +extern crate client_traits; extern crate ethcore; extern crate ethcore_blockchain as blockchain; extern crate ethcore_io as io; diff --git a/ethcore/service/src/service.rs b/ethcore/service/src/service.rs index a1bda778b80..add9eb1d0d6 100644 --- a/ethcore/service/src/service.rs +++ b/ethcore/service/src/service.rs @@ -26,15 +26,17 @@ use io::{IoContext, TimerToken, IoHandler, IoService, IoError}; use sync::PrivateTxHandler; use blockchain::{BlockChainDB, BlockChainDBHandler}; -use ethcore::client::{Client, ClientConfig, ChainNotify, ClientIoMessage}; +use ethcore::client::{Client, ClientConfig, ChainNotify}; use ethcore::miner::Miner; use ethcore::snapshot::service::{Service as SnapshotService, ServiceParams as SnapServiceParams}; use ethcore::snapshot::{SnapshotService as _SnapshotService}; use spec::Spec; use common_types::{ + io_message::ClientIoMessage, errors::{EthcoreError, SnapshotError}, snapshot::RestorationStatus, }; +use client_traits::{ImportBlock, SnapshotClient, Tick}; use ethcore_private_tx::{self, Importer, Signer}; @@ -90,7 +92,7 @@ impl PrivateTxHandler for PrivateTxService { /// Client service setup. Creates and registers client and network services with the IO subsystem. pub struct ClientService { - io_service: Arc>, + io_service: Arc>>, client: Arc, snapshot: Arc, private_tx: Arc, @@ -113,7 +115,7 @@ impl ClientService { private_encryptor_conf: ethcore_private_tx::EncryptorConfig, ) -> Result { - let io_service = IoService::::start()?; + let io_service = IoService::>::start()?; info!("Configured for {} using {} engine", Colour::White.bold().paint(spec.name.clone()), Colour::Yellow.bold().paint(spec.engine.name().to_string())); @@ -165,15 +167,15 @@ impl ClientService { Ok(ClientService { io_service: Arc::new(io_service), - client: client, - snapshot: snapshot, + client, + snapshot, private_tx, database: blockchain_db, }) } /// Get general IO interface - pub fn register_io_handler(&self, handler: Arc + Send>) -> Result<(), IoError> { + pub fn register_io_handler(&self, handler: Arc> + Send>) -> Result<(), IoError> { self.io_service.register_handler(handler) } @@ -193,7 +195,7 @@ impl ClientService { } /// Get network service component - pub fn io(&self) -> Arc> { + pub fn io(&self) -> Arc>> { self.io_service.clone() } @@ -213,8 +215,8 @@ impl ClientService { } /// IO interface for the Client handler -struct ClientIoHandler { - client: Arc, +struct ClientIoHandler { + client: Arc, snapshot: Arc, } @@ -224,13 +226,16 @@ const SNAPSHOT_TICK_TIMER: TimerToken = 1; const CLIENT_TICK: Duration = Duration::from_secs(5); const SNAPSHOT_TICK: Duration = Duration::from_secs(10); -impl IoHandler for ClientIoHandler { - fn initialize(&self, io: &IoContext) { +impl IoHandler> for ClientIoHandler +where + C: ImportBlock + SnapshotClient + Tick + 'static, +{ + fn initialize(&self, io: &IoContext>) { io.register_timer(CLIENT_TICK_TIMER, CLIENT_TICK).expect("Error registering client timer"); io.register_timer(SNAPSHOT_TICK_TIMER, SNAPSHOT_TICK).expect("Error registering snapshot timer"); } - fn timeout(&self, _io: &IoContext, timer: TimerToken) { + fn timeout(&self, _io: &IoContext>, timer: TimerToken) { trace_time!("service::read"); match timer { CLIENT_TICK_TIMER => { @@ -243,7 +248,7 @@ impl IoHandler for ClientIoHandler { } } - fn message(&self, _io: &IoContext, net_message: &ClientIoMessage) { + fn message(&self, _io: &IoContext>, net_message: &ClientIoMessage) { trace_time!("service::message"); use std::thread; diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index 60e4263aefc..bb4855e189e 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity Ethereum. If not, see . -use std::{cmp, ops}; +use std::cmp; use std::collections::{HashSet, BTreeMap, VecDeque}; use std::sync::atomic::{AtomicUsize, AtomicBool, Ordering as AtomicOrdering}; use std::sync::{Arc, Weak}; @@ -42,14 +42,15 @@ use client::ancient_import::AncientVerifier; use client::{ ReopenBlock, PrepareOpenBlock, ImportSealedBlock, BroadcastProposalBlock, Call, BlockProducer, SealedBlockImporter, ChainNotify, EngineInfo, - ClientConfig, NewBlocks, ChainRoute, ChainMessageType, bad_blocks, ClientIoMessage, + ClientConfig, NewBlocks, ChainRoute, ChainMessageType, bad_blocks, }; use client_traits::{ BlockInfo, ScheduleInfo, StateClient, BlockChainReset, Nonce, Balance, ChainInfo, TransactionInfo, ImportBlock, AccountData, BlockChain as BlockChainTrait, BlockChainClient, - IoClient, BadBlocks, ProvingBlockChainClient, - StateOrBlock + IoClient, BadBlocks, ProvingBlockChainClient, SnapshotClient, + DatabaseRestore, SnapshotWriter, Tick, + StateOrBlock, }; use engine::Engine; use machine::{ @@ -59,7 +60,7 @@ use machine::{ }; use trie_vm_factories::{Factories, VmFactory}; use miner::{Miner, MinerService}; -use snapshot::{self, io as snapshot_io, SnapshotClient}; +use snapshot; use spec::Spec; use account_state::State; use executive_state; @@ -71,6 +72,8 @@ use types::{ block::PreverifiedBlock, block_status::BlockStatus, blockchain_info::BlockChainInfo, + client_types::ClientReport, + io_message::ClientIoMessage, encoded, engines::{ ForkChoice, @@ -111,44 +114,6 @@ const MAX_ANCIENT_BLOCKS_TO_IMPORT: usize = 4; const MAX_QUEUE_SIZE_TO_SLEEP_ON: usize = 2; const MIN_HISTORY_SIZE: u64 = 8; -/// Report on the status of a client. -#[derive(Default, Clone, Debug, Eq, PartialEq)] -pub struct ClientReport { - /// How many blocks have been imported so far. - pub blocks_imported: usize, - /// How many transactions have been applied so far. - pub transactions_applied: usize, - /// How much gas has been processed so far. - pub gas_processed: U256, - /// Memory used by state DB - pub state_db_mem: usize, -} - -impl ClientReport { - /// Alter internal reporting to reflect the additional `block` has been processed. - pub fn accrue_block(&mut self, header: &Header, transactions: usize) { - self.blocks_imported += 1; - self.transactions_applied += transactions; - self.gas_processed = self.gas_processed + *header.gas_used(); - } -} - -impl<'a> ops::Sub<&'a ClientReport> for ClientReport { - type Output = Self; - - fn sub(mut self, other: &'a ClientReport) -> Self { - let higher_mem = cmp::max(self.state_db_mem, other.state_db_mem); - let lower_mem = cmp::min(self.state_db_mem, other.state_db_mem); - - self.blocks_imported -= other.blocks_imported; - self.transactions_applied -= other.transactions_applied; - self.gas_processed = self.gas_processed - other.gas_processed; - self.state_db_mem = higher_mem - lower_mem; - - self - } -} - struct SleepState { last_activity: Option, last_autosleep: Option, @@ -171,7 +136,7 @@ struct Importer { pub verifier: Box>, /// Queue containing pending blocks - pub block_queue: BlockQueue, + pub block_queue: BlockQueue, /// Handles block sealing pub miner: Arc, @@ -222,7 +187,7 @@ pub struct Client { /// Flag changed by `sleep` and `wake_up` methods. Not to be confused with `enabled`. liveness: AtomicBool, - io_channel: RwLock>, + io_channel: RwLock>>, /// List of actors to be notified on certain chain events notify: RwLock>>, @@ -261,7 +226,7 @@ impl Importer { pub fn new( config: &ClientConfig, engine: Arc, - message_channel: IoChannel, + message_channel: IoChannel>, miner: Arc, ) -> Result { let block_queue = BlockQueue::new( @@ -723,7 +688,7 @@ impl Client { spec: &Spec, db: Arc, miner: Arc, - message_channel: IoChannel, + message_channel: IoChannel>, ) -> Result, EthcoreError> { let trie_spec = match config.fat_db { true => TrieSpec::Fat, @@ -948,11 +913,6 @@ impl Client { Arc::new(last_hashes) } - /// This is triggered by a message coming from a block queue when the block is ready for insertion - pub fn import_verified_blocks(&self) -> usize { - self.importer.import_verified_blocks(self) - } - // use a state-proving closure for the given block. fn with_proving_caller(&self, id: BlockId, with_call: F) -> T where F: FnOnce(&MachineCall) -> T @@ -1037,7 +997,7 @@ impl Client { } /// Replace io channel. Useful for testing. - pub fn set_io_channel(&self, io_channel: IoChannel) { + pub fn set_io_channel(&self, io_channel: IoChannel>) { *self.io_channel.write() = io_channel; } @@ -1112,15 +1072,6 @@ impl Client { report } - /// Tick the client. - // TODO: manage by real events. - pub fn tick(&self, prevent_sleep: bool) { - self.check_garbage(); - if !prevent_sleep { - self.check_snooze(); - } - } - fn check_garbage(&self) { self.chain.read().collect_garbage(); self.importer.block_queue.collect_garbage(); @@ -1161,64 +1112,6 @@ impl Client { } } - /// Take a snapshot at the given block. - /// If the ID given is "latest", this will default to 1000 blocks behind. - pub fn take_snapshot( - &self, - writer: W, - at: BlockId, - p: &Progress, - ) -> Result<(), EthcoreError> { - if let Snapshotting::Unsupported = self.engine.snapshot_mode() { - return Err(EthcoreError::Snapshot(SnapshotError::SnapshotsUnsupported)); - } - let db = self.state_db.read().journal_db().boxed_clone(); - let best_block_number = self.chain_info().best_block_number; - let block_number = self.block_number(at).ok_or_else(|| SnapshotError::InvalidStartingBlock(at))?; - - if db.is_prunable() && self.pruning_info().earliest_state > block_number { - return Err(SnapshotError::OldBlockPrunedDB.into()); - } - - let history = cmp::min(self.history, 1000); - - let start_hash = match at { - BlockId::Latest => { - let start_num = match db.earliest_era() { - Some(era) => cmp::max(era, best_block_number.saturating_sub(history)), - None => best_block_number.saturating_sub(history), - }; - - match self.block_hash(BlockId::Number(start_num)) { - Some(h) => h, - None => return Err(SnapshotError::InvalidStartingBlock(at).into()), - } - } - _ => match self.block_hash(at) { - Some(hash) => hash, - None => return Err(SnapshotError::InvalidStartingBlock(at).into()), - }, - }; - - let processing_threads = self.config.snapshot.processing_threads; - let chunker = snapshot::chunker(self.engine.snapshot_mode()).ok_or_else(|| SnapshotError::SnapshotsUnsupported)?; - snapshot::take_snapshot( - chunker, - &self.chain.read(), - start_hash, - db.as_hash_db(), - writer, - p, - processing_threads, - )?; - Ok(()) - } - - /// Ask the client what the history parameter is. - pub fn pruning_history(&self) -> u64 { - self.history - } - fn block_hash(chain: &BlockChain, id: BlockId) -> Option { match id { BlockId::Hash(hash) => Some(hash), @@ -1342,7 +1235,7 @@ impl Client { } } -impl snapshot::DatabaseRestore for Client { +impl DatabaseRestore for Client { /// Restart the client with a new backend fn restore_db(&self, new_db: &str) -> Result<(), EthcoreError> { trace!(target: "snapshot", "Replacing client database with {:?}", new_db); @@ -1426,6 +1319,11 @@ impl BlockChainReset for Client { Ok(()) } + + /// Ask the client what the history parameter is. + fn pruning_history(&self) -> u64 { + self.history + } } impl Nonce for Client { @@ -1547,6 +1445,11 @@ impl ImportBlock for Client { Err((_, e)) => Err(e), } } + + /// Triggered by a message from a block queue when the block is ready for insertion + fn import_verified_blocks(&self) -> usize { + self.importer.import_verified_blocks(self) + } } impl StateClient for Client { @@ -2341,6 +2244,18 @@ impl IoClient for Client { } } } + +} + +impl Tick for Client { + /// Tick the client. + // TODO: manage by real events. + fn tick(&self, prevent_sleep: bool) { + self.check_garbage(); + if !prevent_sleep { + self.check_snooze(); + } + } } impl ReopenBlock for Client { @@ -2581,7 +2496,60 @@ impl ProvingBlockChainClient for Client { } } -impl SnapshotClient for Client {} +impl SnapshotClient for Client { + fn take_snapshot( + &self, + writer: W, + at: BlockId, + p: &Progress, + ) -> Result<(), EthcoreError> { + if let Snapshotting::Unsupported = self.engine.snapshot_mode() { + return Err(EthcoreError::Snapshot(SnapshotError::SnapshotsUnsupported)); + } + let db = self.state_db.read().journal_db().boxed_clone(); + let best_block_number = self.chain_info().best_block_number; + let block_number = self.block_number(at).ok_or_else(|| SnapshotError::InvalidStartingBlock(at))?; + + if db.is_prunable() && self.pruning_info().earliest_state > block_number { + return Err(SnapshotError::OldBlockPrunedDB.into()); + } + + let history = cmp::min(self.history, 1000); + + let start_hash = match at { + BlockId::Latest => { + let start_num = match db.earliest_era() { + Some(era) => cmp::max(era, best_block_number.saturating_sub(history)), + None => best_block_number.saturating_sub(history), + }; + + match self.block_hash(BlockId::Number(start_num)) { + Some(h) => h, + None => return Err(SnapshotError::InvalidStartingBlock(at).into()), + } + } + _ => match self.block_hash(at) { + Some(hash) => hash, + None => return Err(SnapshotError::InvalidStartingBlock(at).into()), + }, + }; + + let processing_threads = self.config.snapshot.processing_threads; + let chunker = snapshot::chunker(self.engine.snapshot_mode()).ok_or_else(|| SnapshotError::SnapshotsUnsupported)?; + snapshot::take_snapshot( + chunker, + &self.chain.read(), + start_hash, + db.as_hash_db(), + writer, + p, + processing_threads, + )?; + Ok(()) + } + + +} /// Returns `LocalizedReceipt` given `LocalizedTransaction` /// and a vector of receipts from given block up to transaction index. @@ -2641,7 +2609,7 @@ impl IoChannelQueue { } } - pub fn queue(&self, channel: &IoChannel, count: usize, fun: F) -> EthcoreResult<()> where + pub fn queue(&self, channel: &IoChannel>, count: usize, fun: F) -> EthcoreResult<()> where F: Fn(&Client) + Send + Sync + 'static, { let queue_size = self.currently_queued.load(AtomicOrdering::Relaxed); diff --git a/ethcore/src/client/mod.rs b/ethcore/src/client/mod.rs index 60e36d172a0..58b8b7ffa65 100644 --- a/ethcore/src/client/mod.rs +++ b/ethcore/src/client/mod.rs @@ -22,15 +22,13 @@ mod client; mod config; #[cfg(any(test, feature = "test-helpers"))] mod evm_test_client; -mod io_message; #[cfg(any(test, feature = "test-helpers"))] mod test_client; -pub use self::client::{Client, ClientReport}; +pub use self::client::Client; pub use self::config::{ClientConfig, DatabaseCompactionProfile, BlockChainConfig, VMType}; #[cfg(any(test, feature = "test-helpers"))] pub use self::evm_test_client::{EvmTestClient, EvmTestError, TransactErr, TransactSuccess}; -pub use self::io_message::ClientIoMessage; #[cfg(any(test, feature = "test-helpers"))] pub use self::test_client::{TestBlockChainClient, EachBlockWith, TestState}; pub use self::chain_notify::{ChainNotify, NewBlocks, ChainRoute, ChainRouteType, ChainMessageType}; diff --git a/ethcore/src/client/test_client.rs b/ethcore/src/client/test_client.rs index 6f243cb4c45..51cbed75e2a 100644 --- a/ethcore/src/client/test_client.rs +++ b/ethcore/src/client/test_client.rs @@ -592,6 +592,10 @@ impl ImportBlock for TestBlockChainClient { } Ok(h) } + + fn import_verified_blocks(&self) -> usize { + unimplemented!("TestClient does not implement import_verified_blocks()") + } } impl Call for TestBlockChainClient { diff --git a/ethcore/src/json_tests/chain.rs b/ethcore/src/json_tests/chain.rs index 4bfe3c7c962..28e1f567319 100644 --- a/ethcore/src/json_tests/chain.rs +++ b/ethcore/src/json_tests/chain.rs @@ -100,7 +100,6 @@ pub fn json_chain_test(json_data: &[u8], start_stop_ho if let Ok(block) = Unverified::from_rlp(b) { let _ = client.import_block(block); client.flush_queue(); - client.import_verified_blocks(); } } fail_unless(client.chain_info().best_block_hash == blockchain.best_block.into()); diff --git a/ethcore/src/lib.rs b/ethcore/src/lib.rs index a34db6c6522..8beaf991f53 100644 --- a/ethcore/src/lib.rs +++ b/ethcore/src/lib.rs @@ -69,7 +69,6 @@ extern crate ethcore_io as io; extern crate ethcore_miner; extern crate ethereum_types; extern crate executive_state; -extern crate trie_vm_factories; extern crate futures; extern crate hash_db; extern crate itertools; @@ -77,10 +76,6 @@ extern crate journaldb; extern crate keccak_hash as hash; extern crate keccak_hasher; extern crate kvdb; -#[cfg(any(test, feature = "test-helpers"))] -extern crate kvdb_memorydb; - -extern crate len_caching_lock; extern crate machine; extern crate memory_cache; extern crate num_cpus; @@ -92,18 +87,15 @@ extern crate patricia_trie_ethereum as ethtrie; extern crate rand; extern crate rayon; extern crate rlp; -extern crate parity_util_mem; -extern crate parity_util_mem as malloc_size_of; -#[cfg(any(test, feature = "test-helpers"))] -extern crate rustc_hex; extern crate serde; extern crate spec; extern crate state_db; -extern crate time_utils; extern crate trace; +extern crate trie_vm_factories; extern crate triehash_ethereum as triehash; extern crate unexpected; extern crate using_queue; +extern crate verification; extern crate vm; #[cfg(test)] @@ -119,8 +111,8 @@ extern crate ethash; extern crate ethkey; #[cfg(any(test, feature = "test-helpers"))] extern crate ethjson; -#[cfg(any(test, feature = "tempdir"))] -extern crate tempdir; +#[cfg(any(test, feature = "test-helpers"))] +extern crate kvdb_memorydb; #[cfg(any(test, feature = "kvdb-rocksdb"))] extern crate kvdb_rocksdb; #[cfg(any(test, feature = "json-tests"))] @@ -137,8 +129,12 @@ extern crate pod; extern crate blooms_db; #[cfg(any(test, feature = "env_logger"))] extern crate env_logger; +#[cfg(any(test, feature = "test-helpers"))] +extern crate rustc_hex; #[cfg(test)] extern crate serde_json; +#[cfg(any(test, feature = "tempdir"))] +extern crate tempdir; #[macro_use] extern crate ethabi_contract; @@ -162,7 +158,6 @@ pub mod block; pub mod client; pub mod miner; pub mod snapshot; -pub mod verification; #[cfg(test)] mod tests; diff --git a/ethcore/src/miner/miner.rs b/ethcore/src/miner/miner.rs index bd12ede1965..47559f1707f 100644 --- a/ethcore/src/miner/miner.rs +++ b/ethcore/src/miner/miner.rs @@ -36,36 +36,30 @@ use miner::pool_client::{PoolClient, CachedNonceClient, NonceCache}; use miner; use parking_lot::{Mutex, RwLock}; use rayon::prelude::*; -use types::transaction::{ - self, - Action, - UnverifiedTransaction, - SignedTransaction, - PendingTransaction, -}; use types::{ BlockNumber, ids::TransactionId, block::Block, header::Header, ids::BlockId, + io_message::ClientIoMessage, engines::{Seal, SealingState}, errors::{EthcoreError as Error, ExecutionError}, receipt::RichReceipt, + transaction::{ + self, + Action, + UnverifiedTransaction, + SignedTransaction, + PendingTransaction, + }, }; use using_queue::{UsingQueue, GetAction}; use block::{ClosedBlock, SealedBlock}; -use client::{ - BlockProducer, SealedBlockImporter, ClientIoMessage, -}; -use client_traits::{ - BlockChain, ChainInfo, Nonce, TransactionInfo, -}; -use engine::{ - Engine, - signer::EngineSigner -}; +use client::{BlockProducer, SealedBlockImporter, Client}; +use client_traits::{BlockChain, ChainInfo, Nonce, TransactionInfo}; +use engine::{Engine, signer::EngineSigner}; use machine::executive::contract_address; use spec::Spec; use account_state::State; @@ -262,7 +256,7 @@ pub struct Miner { transaction_queue: Arc, engine: Arc, accounts: Arc, - io_channel: RwLock>>, + io_channel: RwLock>>>, service_transaction_checker: Option, } @@ -346,7 +340,7 @@ impl Miner { } /// Sets `IoChannel` - pub fn set_io_channel(&self, io_channel: IoChannel) { + pub fn set_io_channel(&self, io_channel: IoChannel>) { *self.io_channel.write() = Some(io_channel); } @@ -1426,7 +1420,7 @@ impl miner::MinerService for Miner { let accounts = self.accounts.clone(); let service_transaction_checker = self.service_transaction_checker.clone(); - let cull = move |chain: &::client::Client| { + let cull = move |chain: &Client| { let client = PoolClient::new( chain, &nonce_cache, @@ -1437,7 +1431,7 @@ impl miner::MinerService for Miner { queue.cull(client); }; - if let Err(e) = channel.send(ClientIoMessage::execute(cull)) { + if let Err(e) = channel.send(ClientIoMessage::::execute(cull)) { warn!(target: "miner", "Error queueing cull: {:?}", e); } } else { diff --git a/ethcore/src/miner/pool_client.rs b/ethcore/src/miner/pool_client.rs index 97a4d004d84..8b8740dff5d 100644 --- a/ethcore/src/miner/pool_client.rs +++ b/ethcore/src/miner/pool_client.rs @@ -221,30 +221,30 @@ impl<'a, C: 'a> CachedNonceClient<'a, C> { impl<'a, C: 'a> NonceClient for CachedNonceClient<'a, C> where C: Nonce + Sync, { - fn account_nonce(&self, address: &Address) -> U256 { - if let Some(nonce) = self.cache.nonces.read().get(address) { - return *nonce; - } - - // We don't check again if cache has been populated. - // It's not THAT expensive to fetch the nonce from state. - let mut cache = self.cache.nonces.write(); - let nonce = self.client.latest_nonce(address); - cache.insert(*address, nonce); - - if cache.len() < self.cache.limit { - return nonce - } - - debug!(target: "txpool", "NonceCache: reached limit."); - trace_time!("nonce_cache:clear"); - - // Remove excessive amount of entries from the cache - let to_remove: Vec<_> = cache.keys().take(self.cache.limit / 2).cloned().collect(); - for x in to_remove { - cache.remove(&x); - } - - nonce - } + fn account_nonce(&self, address: &Address) -> U256 { + if let Some(nonce) = self.cache.nonces.read().get(address) { + return *nonce; + } + + // We don't check again if cache has been populated. + // It's not THAT expensive to fetch the nonce from state. + let mut cache = self.cache.nonces.write(); + let nonce = self.client.latest_nonce(address); + cache.insert(*address, nonce); + + if cache.len() < self.cache.limit { + return nonce + } + + debug!(target: "txpool", "NonceCache: reached limit."); + trace_time!("nonce_cache:clear"); + + // Remove excessive amount of entries from the cache + let to_remove: Vec<_> = cache.keys().take(self.cache.limit / 2).cloned().collect(); + for x in to_remove { + cache.remove(&x); + } + + nonce + } } diff --git a/ethcore/src/snapshot/io.rs b/ethcore/src/snapshot/io.rs index 5a959932b36..b996651bcf5 100644 --- a/ethcore/src/snapshot/io.rs +++ b/ethcore/src/snapshot/io.rs @@ -26,6 +26,7 @@ use std::fs::{self, File}; use std::path::{Path, PathBuf}; use bytes::Bytes; +use client_traits::SnapshotWriter; use ethereum_types::H256; use rlp::{RlpStream, Rlp}; use types::{ @@ -35,20 +36,6 @@ use types::{ const SNAPSHOT_VERSION: u64 = 2; -/// Something which can write snapshots. -/// Writing the same chunk multiple times will lead to implementation-defined -/// behavior, and is not advised. -pub trait SnapshotWriter { - /// Write a compressed state chunk. - fn write_state_chunk(&mut self, hash: H256, chunk: &[u8]) -> io::Result<()>; - - /// Write a compressed block chunk. - fn write_block_chunk(&mut self, hash: H256, chunk: &[u8]) -> io::Result<()>; - - /// Complete writing. The manifest's chunk lists must be consistent - /// with the chunks written. - fn finish(self, manifest: ManifestData) -> io::Result<()> where Self: Sized; -} // (hash, len, offset) #[derive(RlpEncodable, RlpDecodable)] diff --git a/ethcore/src/snapshot/mod.rs b/ethcore/src/snapshot/mod.rs index ff3faa2c539..66a97719648 100644 --- a/ethcore/src/snapshot/mod.rs +++ b/ethcore/src/snapshot/mod.rs @@ -48,7 +48,8 @@ use bloom_journal::Bloom; use num_cpus; use types::snapshot::ManifestData; -use self::io::SnapshotWriter; +// todo[dvdplm] put back in snapshots once it's extracted +use client_traits::SnapshotWriter; use super::state_db::StateDB; use account_state::Account as StateAccount; @@ -58,7 +59,7 @@ use crossbeam_utils::thread; use rand::{Rng, rngs::OsRng}; pub use self::consensus::*; -pub use self::service::{SnapshotClient, Service, DatabaseRestore}; +pub use self::service::Service; pub use self::traits::{SnapshotService, SnapshotComponents, Rebuilder}; pub use self::watcher::Watcher; pub use types::basic_account::BasicAccount; diff --git a/ethcore/src/snapshot/service.rs b/ethcore/src/snapshot/service.rs index cdc0d6a1888..6ca50d70636 100644 --- a/ethcore/src/snapshot/service.rs +++ b/ethcore/src/snapshot/service.rs @@ -29,16 +29,21 @@ use super::{ SnapshotService, Rebuilder, MAX_CHUNK_SIZE, - io::{SnapshotReader, LooseReader, SnapshotWriter, LooseWriter}, + io::{SnapshotReader, LooseReader, LooseWriter}, chunker, }; use blockchain::{BlockChain, BlockChainDB, BlockChainDBHandler}; -use client::{Client, ClientIoMessage}; -use client_traits::{BlockInfo, BlockChainClient, ChainInfo}; +use client::Client; +// todo[dvdplm] put SnapshotWriter back in snapshots once extracted +use client_traits::{ + BlockInfo, BlockChainClient, ChainInfo, + SnapshotClient, SnapshotWriter, DatabaseRestore, +}; use engine::Engine; use hash::keccak; use types::{ + io_message::ClientIoMessage, errors::{EthcoreError as Error, SnapshotError, SnapshotError::UnlinkedAncientBlockChain}, ids::BlockId, snapshot::{ManifestData, Progress, RestorationStatus}, @@ -73,12 +78,6 @@ impl Drop for Guard { } } -/// External database restoration handler -pub trait DatabaseRestore: Send + Sync { - /// Restart with a new backend. Takes ownership of passed database and moves it to a new location. - fn restore_db(&self, new_db: &str) -> Result<(), Error>; -} - /// State restoration manager. struct Restoration { manifest: ManifestData, @@ -213,10 +212,7 @@ impl Restoration { } /// Type alias for client io channel. -pub type Channel = IoChannel; - -/// Trait alias for the Client Service used -pub trait SnapshotClient: BlockChainClient + BlockInfo + DatabaseRestore {} +pub type Channel = IoChannel>; /// Snapshot service parameters. pub struct ServiceParams { @@ -234,7 +230,7 @@ pub struct ServiceParams { /// Usually "/snapshot" pub snapshot_root: PathBuf, /// A handle for database restoration. - pub client: Arc, + pub client: Arc, } /// `SnapshotService` implementation. @@ -251,7 +247,7 @@ pub struct Service { genesis_block: Bytes, state_chunks: AtomicUsize, block_chunks: AtomicUsize, - client: Arc, + client: Arc, progress: Progress, taking_snapshot: AtomicBool, restoring_snapshot: AtomicBool, @@ -483,7 +479,10 @@ impl Service { /// calling this while a restoration is in progress or vice versa /// will lead to a race condition where the first one to finish will /// have their produced snapshot overwritten. - pub fn take_snapshot(&self, client: &Client, num: u64) -> Result<(), Error> { + pub fn take_snapshot(&self, client: &C, num: u64) -> Result<(), Error> + where + C: ChainInfo + SnapshotClient + { if self.taking_snapshot.compare_and_swap(false, true, Ordering::SeqCst) { info!("Skipping snapshot at #{} as another one is currently in-progress.", num); return Ok(()); @@ -905,13 +904,16 @@ impl Drop for Service { #[cfg(test)] mod tests { - use client::ClientIoMessage; + use client::Client; use io::{IoService}; use spec; use journaldb::Algorithm; use snapshot::SnapshotService; use super::*; - use types::snapshot::{ManifestData, RestorationStatus}; + use types::{ + io_message::ClientIoMessage, + snapshot::{ManifestData, RestorationStatus} + }; use tempdir::TempDir; use test_helpers::{generate_dummy_client_with_spec_and_data, restoration_db_handler}; @@ -919,7 +921,7 @@ mod tests { fn sends_async_messages() { let gas_prices = vec![1.into(), 2.into(), 3.into(), 999.into()]; let client = generate_dummy_client_with_spec_and_data(spec::new_null, 400, 5, &gas_prices); - let service = IoService::::start().unwrap(); + let service = IoService::>::start().unwrap(); let spec = spec::new_test(); let tempdir = TempDir::new("").unwrap(); @@ -932,7 +934,7 @@ mod tests { pruning: Algorithm::Archive, channel: service.channel(), snapshot_root: dir, - client: client, + client, }; let service = Service::new(snapshot_params).unwrap(); diff --git a/ethcore/src/snapshot/tests/helpers.rs b/ethcore/src/snapshot/tests/helpers.rs index c9420fcfcc1..3f23377a5f4 100644 --- a/ethcore/src/snapshot/tests/helpers.rs +++ b/ethcore/src/snapshot/tests/helpers.rs @@ -26,7 +26,7 @@ use account_db::AccountDBMut; use types::basic_account::BasicAccount; use blockchain::{BlockChain, BlockChainDB}; use client::Client; -use client_traits::ChainInfo; +use client_traits::{ChainInfo, SnapshotClient}; use engine::Engine; use snapshot::{StateRebuilder}; use snapshot::io::{SnapshotReader, PackedWriter, PackedReader}; diff --git a/ethcore/src/snapshot/tests/proof_of_work.rs b/ethcore/src/snapshot/tests/proof_of_work.rs index 85982a6df3c..3b6106313c7 100644 --- a/ethcore/src/snapshot/tests/proof_of_work.rs +++ b/ethcore/src/snapshot/tests/proof_of_work.rs @@ -26,8 +26,9 @@ use types::{ use blockchain::generator::{BlockGenerator, BlockBuilder}; use blockchain::{BlockChain, ExtrasInsert}; +use client_traits::SnapshotWriter; use snapshot::{chunk_secondary, Error as SnapshotError, SnapshotComponents}; -use snapshot::io::{PackedReader, PackedWriter, SnapshotReader, SnapshotWriter}; +use snapshot::io::{PackedReader, PackedWriter, SnapshotReader}; use parking_lot::Mutex; use snappy; diff --git a/ethcore/src/snapshot/tests/service.rs b/ethcore/src/snapshot/tests/service.rs index 5702ddf9703..aed14e9b456 100644 --- a/ethcore/src/snapshot/tests/service.rs +++ b/ethcore/src/snapshot/tests/service.rs @@ -22,14 +22,14 @@ use std::sync::Arc; use tempdir::TempDir; use blockchain::BlockProvider; use client::{Client, ClientConfig}; -use client_traits::{BlockInfo, ImportBlock}; +use client_traits::{BlockInfo, ImportBlock, SnapshotWriter}; use types::{ ids::BlockId, snapshot::Progress, verification::Unverified, snapshot::{ManifestData, RestorationStatus}, }; -use snapshot::io::{PackedReader, PackedWriter, SnapshotReader, SnapshotWriter}; +use snapshot::io::{PackedReader, PackedWriter, SnapshotReader}; use snapshot::service::{Service, ServiceParams}; use snapshot::{chunk_state, chunk_secondary, SnapshotService}; use spec; @@ -77,7 +77,7 @@ fn restored_is_equivalent() { }; let service = Service::new(service_params).unwrap(); - service.take_snapshot(&client, NUM_BLOCKS as u64).unwrap(); + service.take_snapshot(&*client, NUM_BLOCKS as u64).unwrap(); let manifest = service.manifest().unwrap(); @@ -226,7 +226,6 @@ fn keep_ancient_blocks() { client2.import_block(Unverified::from_rlp(block.into_inner()).unwrap()).unwrap(); } - client2.import_verified_blocks(); client2.flush_queue(); // Restore the Snapshot @@ -304,7 +303,7 @@ fn recover_aborted_recovery() { }; let service = Service::new(service_params).unwrap(); - service.take_snapshot(&client, NUM_BLOCKS as u64).unwrap(); + service.take_snapshot(&*client, NUM_BLOCKS as u64).unwrap(); let manifest = service.manifest().unwrap(); service.init_restore(manifest.clone(), true).unwrap(); diff --git a/ethcore/src/snapshot/tests/state.rs b/ethcore/src/snapshot/tests/state.rs index d78f33d8d52..50a505e3e71 100644 --- a/ethcore/src/snapshot/tests/state.rs +++ b/ethcore/src/snapshot/tests/state.rs @@ -24,9 +24,10 @@ use types::{ basic_account::BasicAccount, errors::EthcoreError as Error, }; +use client_traits::SnapshotWriter; use snapshot::account; use snapshot::{chunk_state, Error as SnapshotError, Progress, StateRebuilder, SNAPSHOT_SUBPARTS}; -use snapshot::io::{PackedReader, PackedWriter, SnapshotReader, SnapshotWriter}; +use snapshot::io::{PackedReader, PackedWriter, SnapshotReader}; use super::helpers::StateProducer; use rand::SeedableRng; use rand_xorshift::XorShiftRng; diff --git a/ethcore/src/snapshot/watcher.rs b/ethcore/src/snapshot/watcher.rs index 4fc9d881f63..828fb8d4d45 100644 --- a/ethcore/src/snapshot/watcher.rs +++ b/ethcore/src/snapshot/watcher.rs @@ -17,9 +17,12 @@ //! Watcher for snapshot-related chain events. use parking_lot::Mutex; -use client::{Client, ChainNotify, NewBlocks, ClientIoMessage}; +use client::{Client, ChainNotify, NewBlocks}; use client_traits::BlockInfo; -use types::ids::BlockId; +use types::{ + ids::BlockId, + io_message::ClientIoMessage, +}; use io::IoChannel; use ethereum_types::H256; @@ -55,7 +58,7 @@ trait Broadcast: Send + Sync { fn take_at(&self, num: Option); } -impl Broadcast for Mutex> { +impl Broadcast for Mutex>> { fn take_at(&self, num: Option) { let num = match num { Some(n) => n, @@ -83,7 +86,7 @@ impl Watcher { /// Create a new `Watcher` which will trigger a snapshot event /// once every `period` blocks, but only after that block is /// `history` blocks old. - pub fn new(client: Arc, sync_status: F, channel: IoChannel, period: u64, history: u64) -> Self + pub fn new(client: Arc, sync_status: F, channel: IoChannel>, period: u64, history: u64) -> Self where F: 'static + Send + Sync + Fn() -> bool { Watcher { diff --git a/ethcore/src/test_helpers.rs b/ethcore/src/test_helpers.rs index 4ab63846a0a..a89b342def5 100644 --- a/ethcore/src/test_helpers.rs +++ b/ethcore/src/test_helpers.rs @@ -186,7 +186,6 @@ pub fn generate_dummy_client_with_spec_and_data(test_spec: F, block_number: u db = b.drain().state.drop().1; } client.flush_queue(); - client.import_verified_blocks(); client } @@ -239,7 +238,6 @@ pub fn push_block_with_transactions(client: &Arc, transactions: &[Signed } client.flush_queue(); - client.import_verified_blocks(); } /// Creates dummy client (not test client) with corresponding blocks @@ -261,7 +259,6 @@ pub fn get_test_client_with_blocks(blocks: Vec) -> Arc { } } client.flush_queue(); - client.import_verified_blocks(); client } diff --git a/ethcore/src/tests/client.rs b/ethcore/src/tests/client.rs index b376b3c0f62..5ffa201b7a8 100644 --- a/ethcore/src/tests/client.rs +++ b/ethcore/src/tests/client.rs @@ -32,7 +32,10 @@ use types::{ }; use client::{Client, ClientConfig, PrepareOpenBlock, ImportSealedBlock}; -use client_traits::{BlockInfo, BlockChainClient, BlockChainReset, ChainInfo, ImportBlock}; +use client_traits::{ + BlockInfo, BlockChainClient, BlockChainReset, ChainInfo, + ImportBlock, Tick, +}; use spec; use machine::executive::{Executive, TransactOptions}; use miner::{Miner, PendingOrdering, MinerService}; @@ -55,7 +58,6 @@ fn imports_from_empty() { Arc::new(Miner::new_for_tests(&spec, None)), IoChannel::disconnected(), ).unwrap(); - client.import_verified_blocks(); client.flush_queue(); } @@ -102,7 +104,6 @@ fn imports_good_block() { panic!("error importing block being good by definition"); } client.flush_queue(); - client.import_verified_blocks(); let block = client.block_header(BlockId::Number(1)).unwrap(); assert!(!block.into_inner().is_empty()); diff --git a/ethcore/src/tests/trace.rs b/ethcore/src/tests/trace.rs index 26cb7e2bece..76d7234d176 100644 --- a/ethcore/src/tests/trace.rs +++ b/ethcore/src/tests/trace.rs @@ -181,7 +181,6 @@ fn can_trace_block_and_uncle_reward() { block.drain(); client.flush_queue(); - client.import_verified_blocks(); // Test0. Check overall filter let filter = TraceFilter { diff --git a/ethcore/sync/src/tests/consensus.rs b/ethcore/sync/src/tests/consensus.rs index 8879897f0ea..1223678046b 100644 --- a/ethcore/sync/src/tests/consensus.rs +++ b/ethcore/sync/src/tests/consensus.rs @@ -20,11 +20,14 @@ use ethereum_types::{U256, Address}; use io::{IoHandler, IoChannel}; use client_traits::ChainInfo; use engine::signer; -use ethcore::client::{ClientIoMessage}; use spec; +use ethcore::client::Client; use ethcore::miner::{self, MinerService}; use ethkey::{KeyPair, Secret}; -use types::transaction::{Action, PendingTransaction, Transaction}; +use types::{ + io_message::ClientIoMessage, + transaction::{Action, PendingTransaction, Transaction} +}; use super::helpers::*; use SyncConfig; @@ -47,8 +50,8 @@ fn authority_round() { let chain_id = spec::new_test_round().chain_id(); let mut net = TestNet::with_spec(2, SyncConfig::default(), spec::new_test_round); - let io_handler0: Arc> = Arc::new(TestIoHandler::new(net.peer(0).chain.clone())); - let io_handler1: Arc> = Arc::new(TestIoHandler::new(net.peer(1).chain.clone())); + let io_handler0: Arc>> = Arc::new(TestIoHandler::new(net.peer(0).chain.clone())); + let io_handler1: Arc>> = Arc::new(TestIoHandler::new(net.peer(1).chain.clone())); // Push transaction to both clients. Only one of them gets lucky to produce a block. net.peer(0).miner.set_author(miner::Author::Sealer(signer::from_keypair(s0.clone()))); net.peer(1).miner.set_author(miner::Author::Sealer(signer::from_keypair(s1.clone()))); @@ -115,7 +118,7 @@ fn authority_round() { net.peer(1).chain.engine().step(); net.peer(1).chain.engine().step(); assert_eq!(net.peer(1).chain.chain_info().best_block_number, 5); - // Reorg to the longest chain one not ealier view one. + // Reorg to the longest chain one not earlier view one. net.sync(); let ci0 = net.peer(0).chain.chain_info(); let ci1 = net.peer(1).chain.chain_info(); diff --git a/ethcore/sync/src/tests/helpers.rs b/ethcore/sync/src/tests/helpers.rs index b991480788f..666d362ebb5 100644 --- a/ethcore/sync/src/tests/helpers.rs +++ b/ethcore/sync/src/tests/helpers.rs @@ -22,9 +22,10 @@ use bytes::Bytes; use network::{self, PeerId, ProtocolId, PacketId, SessionInfo}; use network::client_version::ClientVersion; use tests::snapshot::*; +use types::io_message::ClientIoMessage; use client_traits::BlockChainClient; use ethcore::client::{TestBlockChainClient, Client as EthcoreClient, - ClientConfig, ChainNotify, NewBlocks, ChainMessageType, ClientIoMessage}; + ClientConfig, ChainNotify, NewBlocks, ChainMessageType}; use ethcore::snapshot::SnapshotService; use spec::{self, Spec}; use ethcore_private_tx::PrivateStateDB; @@ -554,8 +555,8 @@ impl TestIoHandler { } } -impl IoHandler for TestIoHandler { - fn message(&self, _io: &IoContext, net_message: &ClientIoMessage) { +impl IoHandler> for TestIoHandler { + fn message(&self, _io: &IoContext>, net_message: &ClientIoMessage) { match *net_message { ClientIoMessage::Execute(ref exec) => { *self.private_tx_queued.lock() += 1; diff --git a/ethcore/sync/src/tests/private.rs b/ethcore/sync/src/tests/private.rs index aabcaa82566..50c361c9f56 100644 --- a/ethcore/sync/src/tests/private.rs +++ b/ethcore/sync/src/tests/private.rs @@ -18,12 +18,15 @@ use std::sync::Arc; use hash::keccak; use io::{IoHandler, IoChannel}; use types::transaction::{Transaction, Action}; -use types::ids::BlockId; +use types::{ + ids::BlockId, + io_message::ClientIoMessage, +}; use client_traits::BlockChainClient; use engine::signer; use ethcore::{ + client::Client, CreateContractAddress, - client::ClientIoMessage, miner::{self, MinerService}, test_helpers::{push_block_with_transactions, new_db}, }; @@ -52,8 +55,8 @@ fn send_private_transaction() { let mut net = TestNet::with_spec(2, SyncConfig::default(), seal_spec); let client0 = net.peer(0).chain.clone(); let client1 = net.peer(1).chain.clone(); - let io_handler0: Arc> = Arc::new(TestIoHandler::new(net.peer(0).chain.clone())); - let io_handler1: Arc> = Arc::new(TestIoHandler::new(net.peer(1).chain.clone())); + let io_handler0: Arc>> = Arc::new(TestIoHandler::new(net.peer(0).chain.clone())); + let io_handler1: Arc>> = Arc::new(TestIoHandler::new(net.peer(1).chain.clone())); net.peer(0).miner.set_author(miner::Author::Sealer(signer::from_keypair(s0.clone()))); net.peer(1).miner.set_author(miner::Author::Sealer(signer::from_keypair(s1.clone()))); @@ -65,7 +68,7 @@ fn send_private_transaction() { let (address, _) = contract_address(CreateContractAddress::FromSenderAndNonce, &s0.address(), &0.into(), &[]); let chain_id = client0.signing_chain_id(); - // Exhange statuses + // Exchange statuses net.sync(); // Setup private providers @@ -173,8 +176,8 @@ fn sync_private_state() { let mut net = TestNet::with_spec(2, SyncConfig::default(), seal_spec); let client0 = net.peer(0).chain.clone(); let client1 = net.peer(1).chain.clone(); - let io_handler0: Arc> = Arc::new(TestIoHandler::new(net.peer(0).chain.clone())); - let io_handler1: Arc> = Arc::new(TestIoHandler::new(net.peer(1).chain.clone())); + let io_handler0: Arc>> = Arc::new(TestIoHandler::new(net.peer(0).chain.clone())); + let io_handler1: Arc>> = Arc::new(TestIoHandler::new(net.peer(1).chain.clone())); net.peer(0).miner.set_author(miner::Author::Sealer(signer::from_keypair(s0.clone()))); net.peer(1).miner.set_author(miner::Author::Sealer(signer::from_keypair(s1.clone()))); diff --git a/ethcore/types/src/client_types.rs b/ethcore/types/src/client_types.rs index ad90e0db0d6..a67eebcab1f 100644 --- a/ethcore/types/src/client_types.rs +++ b/ethcore/types/src/client_types.rs @@ -18,8 +18,12 @@ use std::{ fmt::{Display, Formatter, Error as FmtError}, + ops, + cmp, time::Duration, }; +use ethereum_types::U256; +use crate::header::Header; /// Operating mode for the client. #[derive(Debug, Eq, PartialEq, Clone)] @@ -47,3 +51,41 @@ impl Display for Mode { } } +/// Report on the status of a client. +#[derive(Default, Clone, Debug, Eq, PartialEq)] +pub struct ClientReport { + /// How many blocks have been imported so far. + pub blocks_imported: usize, + /// How many transactions have been applied so far. + pub transactions_applied: usize, + /// How much gas has been processed so far. + pub gas_processed: U256, + /// Memory used by state DB + pub state_db_mem: usize, +} + +impl ClientReport { + /// Alter internal reporting to reflect the additional `block` has been processed. + pub fn accrue_block(&mut self, header: &Header, transactions: usize) { + self.blocks_imported += 1; + self.transactions_applied += transactions; + self.gas_processed = self.gas_processed + *header.gas_used(); + } +} + +impl<'a> ops::Sub<&'a ClientReport> for ClientReport { + type Output = Self; + + fn sub(mut self, other: &'a ClientReport) -> Self { + let higher_mem = cmp::max(self.state_db_mem, other.state_db_mem); + let lower_mem = cmp::min(self.state_db_mem, other.state_db_mem); + + self.blocks_imported -= other.blocks_imported; + self.transactions_applied -= other.transactions_applied; + self.gas_processed = self.gas_processed - other.gas_processed; + self.state_db_mem = higher_mem - lower_mem; + + self + } +} + diff --git a/ethcore/src/client/io_message.rs b/ethcore/types/src/io_message.rs similarity index 78% rename from ethcore/src/client/io_message.rs rename to ethcore/types/src/io_message.rs index 1b4725da51c..d475cb1b377 100644 --- a/ethcore/src/client/io_message.rs +++ b/ethcore/types/src/io_message.rs @@ -14,15 +14,17 @@ // You should have received a copy of the GNU General Public License // along with Parity Ethereum. If not, see . +//! Defines the `ClientIoMessage` type, used pervasively throughout various parts of the project to +//! communicate between each other. + use std::fmt; use bytes::Bytes; -use client::Client; use ethereum_types::H256; -use types::snapshot::ManifestData; +use crate::snapshot::ManifestData; /// Message type for external and internal events #[derive(Debug)] -pub enum ClientIoMessage { +pub enum ClientIoMessage { /// Best Block Hash in chain has been changed NewChainHead, /// A block is ready @@ -36,20 +38,20 @@ pub enum ClientIoMessage { /// Take a snapshot for the block with given number. TakeSnapshot(u64), /// Execute wrapped closure - Execute(Callback), + Execute(Callback), } -impl ClientIoMessage { +impl ClientIoMessage { /// Create new `ClientIoMessage` that executes given procedure. - pub fn execute(fun: F) -> Self { + pub fn execute(fun: F) -> Self { ClientIoMessage::Execute(Callback(Box::new(fun))) } } /// A function to invoke in the client thread. -pub struct Callback(pub Box); +pub struct Callback(pub Box); -impl fmt::Debug for Callback { +impl fmt::Debug for Callback { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "") } diff --git a/ethcore/types/src/lib.rs b/ethcore/types/src/lib.rs index 42a3c6f8166..fb39ad6eb7c 100644 --- a/ethcore/types/src/lib.rs +++ b/ethcore/types/src/lib.rs @@ -71,6 +71,7 @@ pub mod errors; pub mod filter; pub mod header; pub mod ids; +pub mod io_message; pub mod log_entry; pub mod pruning_info; pub mod receipt; diff --git a/ethcore/verification/Cargo.toml b/ethcore/verification/Cargo.toml new file mode 100644 index 00000000000..0a19861a457 --- /dev/null +++ b/ethcore/verification/Cargo.toml @@ -0,0 +1,34 @@ +[package] +description = "Block verification utilities." +name = "verification" +version = "0.1.0" +authors = ["Parity Technologies "] +edition = "2018" +license = "GPL-3.0" + +[dependencies] +blockchain = { package = "ethcore-blockchain", path = "../blockchain" } +call-contract = { package = "ethcore-call-contract", path = "../call-contract" } +client-traits = { path = "../client-traits" } +common-types = { path = "../types" } +engine = { path = "../engine" } +ethcore-io = { path = "../../util/io" } +ethereum-types = "0.6.0" +keccak-hash = "0.2.0" +len-caching-lock = { path = "../../util/len-caching-lock" } +log = "0.4" +num_cpus = "1.2" +parity-bytes = "0.1.0" +parity-util-mem = "0.2.0" +parking_lot = "0.8.0" +rlp = "0.4.2" +time-utils = { path = "../../util/time-utils" } +triehash = { package = "triehash-ethereum", version = "0.2", path = "../../util/triehash-ethereum" } +unexpected = { path = "../../util/unexpected" } + +[dev-dependencies] +ethcore = { path = "../", features = ["test-helpers"] } +ethkey = { path = "../../accounts/ethkey" } +machine = { path = "../machine" } +null-engine = { path = "../engines/null-engine" } +spec = { path = "../spec" } diff --git a/ethcore/src/verification/canon_verifier.rs b/ethcore/verification/src/canon_verifier.rs similarity index 98% rename from ethcore/src/verification/canon_verifier.rs rename to ethcore/verification/src/canon_verifier.rs index c0c60709700..336428caf97 100644 --- a/ethcore/src/verification/canon_verifier.rs +++ b/ethcore/verification/src/canon_verifier.rs @@ -19,7 +19,7 @@ use call_contract::CallContract; use client_traits::BlockInfo; use engine::Engine; -use types::{ +use common_types::{ header::Header, errors::EthcoreError as Error, }; diff --git a/ethcore/src/verification/mod.rs b/ethcore/verification/src/lib.rs similarity index 95% rename from ethcore/src/verification/mod.rs rename to ethcore/verification/src/lib.rs index 16e0e52dd1d..2f4be58dc5f 100644 --- a/ethcore/src/verification/mod.rs +++ b/ethcore/verification/src/lib.rs @@ -18,6 +18,8 @@ use call_contract::CallContract; use client_traits::BlockInfo; +// The MallocSizeOf derive looks for this in the root +use parity_util_mem as malloc_size_of; mod verification; mod verifier; @@ -29,11 +31,6 @@ pub use self::verification::FullFamilyParams; pub use self::verifier::Verifier; pub use self::queue::{BlockQueue, Config as QueueConfig}; -use self::verification::{ - verify_block_basic, - verify_block_unordered, - verify_header_params, -}; use self::canon_verifier::CanonVerifier; use self::noop_verifier::NoopVerifier; diff --git a/ethcore/src/verification/noop_verifier.rs b/ethcore/verification/src/noop_verifier.rs similarity index 98% rename from ethcore/src/verification/noop_verifier.rs rename to ethcore/verification/src/noop_verifier.rs index 3f9a6210f40..149f2798830 100644 --- a/ethcore/src/verification/noop_verifier.rs +++ b/ethcore/verification/src/noop_verifier.rs @@ -18,11 +18,11 @@ use call_contract::CallContract; use client_traits::BlockInfo; -use engine::Engine; -use types::{ +use common_types::{ header::Header, errors::EthcoreError as Error }; +use engine::Engine; use super::{verification, Verifier}; /// A no-op verifier -- this will verify everything it's given immediately. diff --git a/ethcore/src/verification/queue/kind.rs b/ethcore/verification/src/queue/kind.rs similarity index 95% rename from ethcore/src/verification/queue/kind.rs rename to ethcore/verification/src/queue/kind.rs index 937d05abd18..cc4d1167a4e 100644 --- a/ethcore/src/verification/queue/kind.rs +++ b/ethcore/verification/src/queue/kind.rs @@ -21,7 +21,7 @@ use engine::Engine; use parity_util_mem::MallocSizeOf; use ethereum_types::{H256, U256}; -use types::errors::EthcoreError as Error; +use common_types::errors::EthcoreError as Error; pub use self::blocks::Blocks; pub use self::headers::Headers; @@ -70,12 +70,13 @@ pub mod blocks { use super::{Kind, BlockLike}; use engine::Engine; - use types::{ + use common_types::{ block::PreverifiedBlock, errors::{EthcoreError as Error, BlockError}, verification::Unverified, }; - use verification::{verify_block_basic, verify_block_unordered}; + use log::{debug, warn}; + use crate::verification::{verify_block_basic, verify_block_unordered}; use ethereum_types::{H256, U256}; @@ -147,11 +148,11 @@ pub mod headers { use super::{Kind, BlockLike}; use engine::Engine; - use types::{ + use common_types::{ header::Header, errors::EthcoreError as Error, }; - use verification::verify_header_params; + use crate::verification::verify_header_params; use ethereum_types::{H256, U256}; diff --git a/ethcore/src/verification/queue/mod.rs b/ethcore/verification/src/queue/mod.rs similarity index 93% rename from ethcore/src/verification/queue/mod.rs rename to ethcore/verification/src/queue/mod.rs index 58754251dd2..70795ca7991 100644 --- a/ethcore/src/verification/queue/mod.rs +++ b/ethcore/verification/src/queue/mod.rs @@ -22,17 +22,19 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering}; use std::sync::Arc; use std::cmp; use std::collections::{VecDeque, HashSet, HashMap}; -use parity_util_mem::{MallocSizeOf, MallocSizeOfExt}; -use ethereum_types::{H256, U256}; -use parking_lot::{Condvar, Mutex, RwLock}; -use io::*; -use engine::Engine; -use client::ClientIoMessage; -use len_caching_lock::LenCachingMutex; -use types::{ +use common_types::{ + block_status::BlockStatus, + io_message::ClientIoMessage, errors::{BlockError, EthcoreError as Error, ImportError}, verification::VerificationQueueInfo as QueueInfo, }; +use ethcore_io::*; +use ethereum_types::{H256, U256}; +use engine::Engine; +use len_caching_lock::LenCachingMutex; +use log::{debug, trace}; +use parity_util_mem::{MallocSizeOf, MallocSizeOfExt}; +use parking_lot::{Condvar, Mutex, RwLock}; use self::kind::{BlockLike, Kind}; @@ -42,10 +44,10 @@ const MIN_MEM_LIMIT: usize = 16384; const MIN_QUEUE_LIMIT: usize = 512; /// Type alias for block queue convenience. -pub type BlockQueue = VerificationQueue; +pub type BlockQueue = VerificationQueue; /// Type alias for header queue convenience. -pub type HeaderQueue = VerificationQueue; +pub type HeaderQueue = VerificationQueue; /// Verification queue configuration #[derive(Debug, PartialEq, Clone)] @@ -84,7 +86,7 @@ impl Default for VerifierSettings { fn default() -> Self { VerifierSettings { scale_verifiers: false, - num_verifiers: ::num_cpus::get(), + num_verifiers: num_cpus::get(), } } } @@ -113,9 +115,8 @@ pub enum Status { Unknown, } -impl Into<::types::block_status::BlockStatus> for Status { - fn into(self) -> ::types::block_status::BlockStatus { - use ::types::block_status::BlockStatus; +impl Into for Status { + fn into(self) -> BlockStatus { match self { Status::Queued => BlockStatus::Queued, Status::Bad => BlockStatus::Bad, @@ -133,12 +134,12 @@ struct Sizes { /// A queue of items to be verified. Sits between network or other I/O and the `BlockChain`. /// Keeps them in the same order as inserted, minus invalid items. -pub struct VerificationQueue { +pub struct VerificationQueue { engine: Arc, more_to_verify: Arc, verification: Arc>, deleting: Arc, - ready_signal: Arc, + ready_signal: Arc>, empty: Arc, processing: RwLock>, // hash to difficulty ticks_since_adjustment: AtomicUsize, @@ -150,13 +151,13 @@ pub struct VerificationQueue { total_difficulty: RwLock, } -struct QueueSignal { +struct QueueSignal { deleting: Arc, signalled: AtomicBool, - message_channel: Mutex>, + message_channel: Mutex>>, } -impl QueueSignal { +impl QueueSignal { fn set_sync(&self) { // Do not signal when we are about to close if self.deleting.load(AtomicOrdering::Relaxed) { @@ -200,9 +201,9 @@ struct Verification { check_seal: bool, } -impl VerificationQueue { +impl VerificationQueue { /// Creates a new queue instance. - pub fn new(config: Config, engine: Arc, message_channel: IoChannel, check_seal: bool) -> Self { + pub fn new(config: Config, engine: Arc, message_channel: IoChannel>, check_seal: bool) -> Self { let verification = Arc::new(Verification { unverified: LenCachingMutex::new(VecDeque::new()), verifying: LenCachingMutex::new(VecDeque::new()), @@ -213,7 +214,7 @@ impl VerificationQueue { verifying: AtomicUsize::new(0), verified: AtomicUsize::new(0), }, - check_seal: check_seal, + check_seal, }); let more_to_verify = Arc::new(Condvar::new()); let deleting = Arc::new(AtomicBool::new(false)); @@ -270,19 +271,19 @@ impl VerificationQueue { } VerificationQueue { - engine: engine, - ready_signal: ready_signal, - more_to_verify: more_to_verify, - verification: verification, - deleting: deleting, + engine, + ready_signal, + more_to_verify, + verification, + deleting, processing: RwLock::new(HashMap::new()), - empty: empty, + empty, ticks_since_adjustment: AtomicUsize::new(0), max_queue_size: cmp::max(config.max_queue_size, MIN_QUEUE_LIMIT), max_mem_use: cmp::max(config.max_mem_use, MIN_MEM_LIMIT), - scale_verifiers: scale_verifiers, - verifier_handles: verifier_handles, - state: state, + scale_verifiers, + verifier_handles, + state, total_difficulty: RwLock::new(0.into()), } } @@ -291,7 +292,7 @@ impl VerificationQueue { verification: Arc>, engine: Arc, wait: Arc, - ready: Arc, + ready: Arc>, empty: Arc, state: Arc<(Mutex, Condvar)>, id: usize, @@ -373,7 +374,7 @@ impl VerificationQueue { // we're next! let mut verified = verification.verified.lock(); let mut bad = verification.bad.lock(); - VerificationQueue::drain_verifying(&mut verifying, &mut verified, &mut bad, &verification.sizes); + VerificationQueue::<_, C>::drain_verifying(&mut verifying, &mut verified, &mut bad, &verification.sizes); true } else { false @@ -388,7 +389,7 @@ impl VerificationQueue { verifying.retain(|e| e.hash != hash); if verifying.front().map_or(false, |x| x.output.is_some()) { - VerificationQueue::drain_verifying(&mut verifying, &mut verified, &mut bad, &verification.sizes); + VerificationQueue::<_, C>::drain_verifying(&mut verifying, &mut verified, &mut bad, &verification.sizes); true } else { false @@ -706,7 +707,7 @@ impl VerificationQueue { } } -impl Drop for VerificationQueue { +impl Drop for VerificationQueue { fn drop(&mut self) { trace!(target: "shutdown", "[VerificationQueue] Closing..."); self.clear(); @@ -734,11 +735,12 @@ impl Drop for VerificationQueue { #[cfg(test)] mod tests { - use io::*; + use ethcore_io::*; use super::{BlockQueue, Config, State}; - use test_helpers::{get_good_dummy_block_seq, get_good_dummy_block}; - use bytes::Bytes; - use types::{ + use ethcore::test_helpers::{get_good_dummy_block_seq, get_good_dummy_block}; + use ethcore::client::Client; + use parity_bytes::Bytes; + use common_types::{ errors::{EthcoreError, ImportError}, verification::Unverified, view, @@ -748,7 +750,7 @@ mod tests { // create a test block queue. // auto_scaling enables verifier adjustment. - fn get_test_queue(auto_scale: bool) -> BlockQueue { + fn get_test_queue(auto_scale: bool) -> BlockQueue { let spec = spec::new_test(); let engine = spec.engine; @@ -773,7 +775,7 @@ mod tests { // TODO better test let spec = spec::new_test(); let engine = spec.engine; - let _ = BlockQueue::new(Config::default(), engine, IoChannel::disconnected(), true); + let _ = BlockQueue::::new(Config::default(), engine, IoChannel::disconnected(), true); } #[test] @@ -853,7 +855,7 @@ mod tests { let engine = spec.engine; let mut config = Config::default(); config.max_mem_use = super::MIN_MEM_LIMIT; // empty queue uses about 15000 - let queue = BlockQueue::new(config, engine, IoChannel::disconnected(), true); + let queue = BlockQueue::::new(config, engine, IoChannel::disconnected(), true); assert!(!queue.queue_info().is_full()); let mut blocks = get_good_dummy_block_seq(50); for b in blocks.drain(..) { @@ -903,7 +905,7 @@ mod tests { let spec = spec::new_test(); let engine = spec.engine; let config = get_test_config(1, false); - let queue = BlockQueue::new(config, engine, IoChannel::disconnected(), true); + let queue = BlockQueue::::new(config, engine, IoChannel::disconnected(), true); assert_eq!(queue.num_verifiers(), 1); } @@ -913,7 +915,7 @@ mod tests { let spec = spec::new_test(); let engine = spec.engine; let config = get_test_config(0, false); - let queue = BlockQueue::new(config, engine, IoChannel::disconnected(), true); + let queue = BlockQueue::::new(config, engine, IoChannel::disconnected(), true); assert_eq!(queue.num_verifiers(), 1); } @@ -923,7 +925,7 @@ mod tests { let spec = spec::new_test(); let engine = spec.engine; let config = get_test_config(10_000, false); - let queue = BlockQueue::new(config, engine, IoChannel::disconnected(), true); + let queue = BlockQueue::::new(config, engine, IoChannel::disconnected(), true); let num_cpus = ::num_cpus::get(); assert_eq!(queue.num_verifiers(), num_cpus); @@ -937,7 +939,7 @@ mod tests { let spec = spec::new_test(); let engine = spec.engine; let config = get_test_config(num_cpus - 1, true); - let queue = BlockQueue::new(config, engine, IoChannel::disconnected(), true); + let queue = BlockQueue::::new(config, engine, IoChannel::disconnected(), true); queue.scale_verifiers(num_cpus); assert_eq!(queue.num_verifiers(), num_cpus); diff --git a/ethcore/src/verification/verification.rs b/ethcore/verification/src/verification.rs similarity index 98% rename from ethcore/src/verification/verification.rs rename to ethcore/verification/src/verification.rs index 4e73a37d337..f4bf48a0668 100644 --- a/ethcore/src/verification/verification.rs +++ b/ethcore/verification/src/verification.rs @@ -24,7 +24,7 @@ use std::collections::HashSet; use std::time::{Duration, SystemTime, UNIX_EPOCH}; -use hash::keccak; +use keccak_hash::keccak; use rlp::Rlp; use triehash::ordered_trie_root; use unexpected::{Mismatch, OutOfBounds}; @@ -33,7 +33,7 @@ use blockchain::*; use call_contract::CallContract; use client_traits::BlockInfo; use engine::Engine; -use types::{ +use common_types::{ BlockNumber, header::Header, errors::{EthcoreError as Error, BlockError}, @@ -366,15 +366,19 @@ mod tests { use std::collections::{BTreeMap, HashMap}; use std::time::{SystemTime, UNIX_EPOCH}; + use ethereum_types::{H256, BloomRef, U256, Address}; use blockchain::{BlockDetails, TransactionAddress, BlockReceipts}; - use bytes::Bytes; - use hash::keccak; + use parity_bytes::Bytes; + use keccak_hash::keccak; use engine::Engine; use ethkey::{Random, Generator}; use spec; - use test_helpers::{create_test_block_with_data, create_test_block}; - use types::{ + use ethcore::{ + client::TestBlockChainClient, + test_helpers::{create_test_block_with_data, create_test_block} + }; + use common_types::{ encoded, engines::params::CommonParams, errors::BlockError::*, @@ -383,6 +387,8 @@ mod tests { }; use rlp; use triehash::ordered_trie_root; + use machine::Machine; + use null_engine::NullEngine; fn check_ok(result: Result<(), Error>) { result.unwrap_or_else(|e| panic!("Block verification failed: {:?}", e)); @@ -518,7 +524,7 @@ mod tests { // additions that need access to state (tx filter in specific) // no existing tests need access to test, so having this not function // is fine. - let client = ::client::TestBlockChainClient::default(); + let client = TestBlockChainClient::default(); let parent = bc.block_header_data(header.parent_hash()) .ok_or(BlockError::UnknownParent(*header.parent_hash()))? .decode()?; @@ -779,11 +785,6 @@ mod tests { #[test] fn dust_protection() { - use ethkey::{Generator, Random}; - use types::transaction::{Transaction, Action}; - use machine::Machine; - use null_engine::NullEngine; - let mut params = CommonParams::default(); params.dust_protection_transition = 0; params.nonce_cap_increment = 2; diff --git a/ethcore/src/verification/verifier.rs b/ethcore/verification/src/verifier.rs similarity index 98% rename from ethcore/src/verification/verifier.rs rename to ethcore/verification/src/verifier.rs index ced7f564967..982eab68feb 100644 --- a/ethcore/src/verification/verifier.rs +++ b/ethcore/verification/src/verifier.rs @@ -18,11 +18,12 @@ use call_contract::CallContract; use client_traits::BlockInfo; -use engine::Engine; -use types::{ +use common_types::{ header::Header, errors::EthcoreError as Error, }; +use engine::Engine; + use super::verification; /// Should be used to verify blocks. diff --git a/parity/blockchain.rs b/parity/blockchain.rs index 85000e385c1..1879752589a 100644 --- a/parity/blockchain.rs +++ b/parity/blockchain.rs @@ -30,7 +30,6 @@ use client_traits::{BlockInfo, BlockChainReset, Nonce, Balance, BlockChainClient use ethcore::{ client::{DatabaseCompactionProfile, VMType}, miner::Miner, - verification::queue::VerifierSettings, }; use ethcore_service::ClientService; use cache::CacheConfig; @@ -48,6 +47,7 @@ use types::{ client_types::Mode, verification::Unverified, }; +use verification::queue::VerifierSettings; #[derive(Debug, PartialEq)] pub enum DataFormat { @@ -234,7 +234,7 @@ fn execute_import_light(cmd: ImportBlockchain) -> Result<(), String> { &cmd.cache_config, &cmd.compaction).map_err(|e| format!("Failed to open database: {:?}", e))?; - // TODO: could epoch signals be avilable at the end of the file? + // TODO: could epoch signals be available at the end of the file? let fetch = ::light::client::fetch::unavailable(); let service = LightClientService::start(config, &spec, fetch, db, cache) .map_err(|e| format!("Failed to start client: {}", e))?; diff --git a/parity/configuration.rs b/parity/configuration.rs index 007436b1e23..2066d590854 100644 --- a/parity/configuration.rs +++ b/parity/configuration.rs @@ -32,8 +32,8 @@ use ethkey::{Secret, Public}; use ethcore::client::{VMType}; use ethcore::miner::{stratum, MinerOptions}; use ethcore::snapshot::SnapshotConfiguration; -use ethcore::verification::queue::VerifierSettings; use miner::pool; +use verification::queue::VerifierSettings; use rpc::{IpcConfiguration, HttpConfiguration, WsConfiguration}; use parity_rpc::NetworkSettings; diff --git a/parity/informant.rs b/parity/informant.rs index 29a278a2a38..60ba59f7beb 100644 --- a/parity/informant.rs +++ b/parity/informant.rs @@ -23,13 +23,13 @@ use std::sync::atomic::{AtomicUsize, AtomicBool, Ordering as AtomicOrdering}; use std::time::{Instant, Duration}; use atty; -use ethcore::client::{ - ChainNotify, NewBlocks, ClientReport, Client, ClientIoMessage -}; -use client_traits::{BlockInfo, ChainInfo, BlockChainClient}; +use ethcore::client::{ChainNotify, NewBlocks, Client}; +use client_traits::{BlockInfo, ChainInfo, BlockChainClient, IoClient}; use types::{ BlockNumber, + client_types::ClientReport, ids::BlockId, + io_message::ClientIoMessage, blockchain_info::BlockChainInfo, verification::VerificationQueueInfo as BlockQueueInfo, snapshot::RestorationStatus, @@ -451,12 +451,16 @@ impl LightChainNotify for Informant { const INFO_TIMER: TimerToken = 0; -impl IoHandler for Informant { - fn initialize(&self, io: &IoContext) { +impl IoHandler> for Informant +where + T: InformantData, + C: client_traits::Tick + 'static, +{ + fn initialize(&self, io: &IoContext>) { io.register_timer(INFO_TIMER, Duration::from_secs(5)).expect("Error registering timer"); } - fn timeout(&self, _io: &IoContext, timer: TimerToken) { + fn timeout(&self, _io: &IoContext>, timer: TimerToken) { if timer == INFO_TIMER && !self.in_shutdown.load(AtomicOrdering::SeqCst) { self.tick(); } diff --git a/parity/lib.rs b/parity/lib.rs index 3d96c070048..2ea24c0bfc8 100644 --- a/parity/lib.rs +++ b/parity/lib.rs @@ -74,6 +74,7 @@ extern crate parity_updater as updater; extern crate parity_version; extern crate registrar; extern crate spec; +extern crate verification; #[macro_use] extern crate log as rlog; diff --git a/parity/run.rs b/parity/run.rs index e53e5b29394..7b88747374c 100644 --- a/parity/run.rs +++ b/parity/run.rs @@ -27,7 +27,7 @@ use ethcore::client::{Client, DatabaseCompactionProfile, VMType}; use ethcore::miner::{self, stratum, Miner, MinerService, MinerOptions}; use ethcore::snapshot::{self, SnapshotConfiguration}; use spec::SpecParams; -use ethcore::verification::queue::VerifierSettings; +use verification::queue::VerifierSettings; use ethcore_logger::{Config as LogConfig, RotatingLogger}; use ethcore_service::ClientService; use ethereum_types::Address; @@ -307,18 +307,18 @@ fn execute_light_impl(cmd: RunCmd, logger: Arc, on_client_rq // start RPCs let deps_for_rpc_apis = Arc::new(rpc_apis::LightDependencies { - signer_service: signer_service, + signer_service, client: client.clone(), sync: light_sync.clone(), net: light_sync.clone(), accounts: account_provider, - logger: logger, + logger, settings: Arc::new(cmd.net_settings), - on_demand: on_demand, + on_demand, cache: cache.clone(), transaction_queue: txq, ws_address: cmd.ws_conf.address(), - fetch: fetch, + fetch, geth_compatibility: cmd.geth_compatibility, experimental_rpcs: cmd.experimental_rpcs, executor: runtime.executor(), @@ -344,7 +344,7 @@ fn execute_light_impl(cmd: RunCmd, logger: Arc, on_client_rq LightNodeInformantData { client: client.clone(), sync: light_sync.clone(), - cache: cache, + cache, }, None, Some(rpc_stats), diff --git a/parity/snapshot.rs b/parity/snapshot.rs index 4a4c9d718b0..c9657b2d6ac 100644 --- a/parity/snapshot.rs +++ b/parity/snapshot.rs @@ -20,6 +20,7 @@ use std::time::Duration; use std::path::{Path, PathBuf}; use std::sync::Arc; +use client_traits::SnapshotClient; use hash::keccak; use ethcore::snapshot::{SnapshotConfiguration, SnapshotService as SS}; use ethcore::snapshot::io::{SnapshotReader, PackedReader, PackedWriter}; diff --git a/rpc/Cargo.toml b/rpc/Cargo.toml index fead96d71c5..ff8fa932515 100644 --- a/rpc/Cargo.toml +++ b/rpc/Cargo.toml @@ -67,6 +67,7 @@ account-state = { path = "../ethcore/account-state" } stats = { path = "../util/stats" } trace = { path = "../ethcore/trace" } vm = { path = "../ethcore/vm" } +verification = { path = "../ethcore/verification" } [dev-dependencies] client-traits = { path = "../ethcore/client-traits" } diff --git a/rpc/src/lib.rs b/rpc/src/lib.rs index 648ec43bf82..5bff9358294 100644 --- a/rpc/src/lib.rs +++ b/rpc/src/lib.rs @@ -89,6 +89,7 @@ extern crate account_state; extern crate stats; extern crate tempdir; extern crate trace; +extern crate verification; extern crate vm; #[cfg(any(test, feature = "ethcore-accounts"))] diff --git a/rpc/src/v1/tests/eth.rs b/rpc/src/v1/tests/eth.rs index 45887ae9a73..062acb10d29 100644 --- a/rpc/src/v1/tests/eth.rs +++ b/rpc/src/v1/tests/eth.rs @@ -24,7 +24,7 @@ use ethcore::client::{Client, ClientConfig}; use ethcore::miner::Miner; use spec::{Genesis, Spec, self}; use ethcore::test_helpers; -use ethcore::verification::VerifierType; +use verification::VerifierType; use ethereum_types::{Address, H256, U256}; use ethjson::blockchain::BlockChain; use ethjson::spec::ForkSpec; @@ -98,7 +98,6 @@ impl EthTester { if let Ok(block) = Unverified::from_rlp(b) { let _ = tester.client.import_block(block); tester.client.flush_queue(); - tester.client.import_verified_blocks(); } } From 5ce249ac64d07fdb71067ad1176a6b085d210b15 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 28 Aug 2019 16:15:50 +0200 Subject: [PATCH 4/7] EIP-1344 Add CHAINID op-code (#10983) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add client-traits crate Move the BlockInfo trait to new crate * New crate `machine` Contains code extracted from ethcore that defines `Machine`, `Externalities` and other execution related code. * Use new machine and client-traits crates in ethcore * Use new crates machine and client-traits instead of ethcore where appropriate * Fix tests * Don't re-export so many types from ethcore::client * Fixing more fallout from removing re-export * fix test * More fallout from not re-exporting types * Add some docs * cleanup * import the macro edition style * Tweak docs * Add missing import * remove unused ethabi_derive imports * Use latest ethabi-contract * Move many traits from ethcore/client/traits to client-traits crate Initial version of extracted Engine trait * Move snapshot related traits to the engine crate (eew) * Move a few snapshot related types to common_types Cleanup Executed as exported from machine crate * fix warning * Gradually introduce new engine crate: snapshot * ethcore typechecks with new engine crate * Sort out types outside ethcore * Add an EpochVerifier to ethash and use that in Engine.epoch_verifier() Cleanup * Document pub members * Sort out tests Sort out default impls for EpochVerifier * Add test-helpers feature and move EngineSigner impl to the right place * Sort out tests * Sort out tests and refactor verification types * Fix missing traits * More missing traits Fix Histogram * Fix tests and cleanup * cleanup * Put back needed logger import * Don't rexport common_types from ethcore/src/client Don't export ethcore::client::* * Remove files no longer used Use types from the engine crate Explicit exports from engine::engine * Get rid of itertools * Move a few more traits from ethcore to client-traits: BlockChainReset, ScheduleInfo, StateClient * Move ProvingBlockChainClient to client-traits * Don't re-export ForkChoice and Transition from ethcore * Address grumbles: sort imports, remove commented out code * Fix merge resolution error * Extract the Clique engine to own crate * Extract NullEngine and the block_reward module from ethcore * Extract InstantSeal engine to own crate * Extract remaining engines * Extract executive_state to own crate so it can be used by engine crates * Remove snapshot stuff from the engine crate * Put snapshot traits back in ethcore * cleanup * Remove stuff from ethcore * Don't use itertools * itertools in aura is legit-ish * More post-merge fixes * Re-export less types in client * cleanup * Extract spec to own crate * Put back the test-helpers from basic-authority * Fix ethcore benchmarks * Reduce the public api of ethcore/verification * WIP * Add Cargo.toml * Fix compilation outside ethcore * Audit uses of import_verified_blocks() and remove unneeded calls Cleanup * cleanup * Remove unused imports from ethcore * Cleanup * remove double semi-colons * Add missing generic param * More missing generics * Update ethcore/block-reward/Cargo.toml Co-Authored-By: Tomasz Drwięga * Update ethcore/engines/basic-authority/Cargo.toml Co-Authored-By: Tomasz Drwięga * Update ethcore/engines/ethash/Cargo.toml Co-Authored-By: Tomasz Drwięga * Update ethcore/engines/clique/src/lib.rs Co-Authored-By: Tomasz Drwięga * signers is already a ref * Add an EngineType enum to tighten up Engine.name() * Add CHAINID opcode * Introduce Snapshotting enum to distinguish the type of snapshots a chain uses * Rename supports_warp to snapshot_mode * Missing import * Add chain_id wherever we instantiate EnvInfo * more missing chain_id * Tell serde to ignore the chain_id field on Env * Update ethcore/src/snapshot/consensus/mod.rs Co-Authored-By: Tomasz Drwięga * Use the chain_id from the machine by adding chain_id() to the Ext trait * cleanup * add missing impl cleanup * missing import * Fix import * Add transition marker for EIP 1344 * double semi * Fix merge problem * cleanup * merge conflict error * Fix a few warnings * Update ethcore/vm/src/schedule.rs Co-Authored-By: Andronik Ordian * more merge fallout --- Cargo.lock | 66 +++++ .../validator-set/src/safe_contract.rs | 2 +- ethcore/evm/Cargo.toml | 1 + ethcore/evm/src/factory.rs | 2 +- ethcore/evm/src/instructions.rs | 10 +- ethcore/evm/src/interpreter/mod.rs | 6 +- ethcore/evm/src/lib.rs | 2 + ethcore/evm/src/tests.rs | 274 ++++++++++-------- ethcore/machine/src/externalities.rs | 4 + ethcore/src/json_tests/executive.rs | 2 + ethcore/types/src/engines/params.rs | 7 + ethcore/vm/src/env_info.rs | 2 +- ethcore/vm/src/ext.rs | 3 + ethcore/vm/src/schedule.rs | 5 + ethcore/vm/src/tests.rs | 16 +- json/src/spec/params.rs | 2 + parity/informant.rs | 2 +- rpc/Cargo.toml | 2 +- rpc/src/lib.rs | 3 +- 19 files changed, 278 insertions(+), 133 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8f866209af1..98940990fae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1631,6 +1631,7 @@ dependencies = [ "bit-set 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "criterion 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)", "ethereum-types 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "hex-literal 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "keccak-hash 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1956,6 +1957,23 @@ dependencies = [ "unicode-segmentation 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "hex-literal" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "hex-literal-impl 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro-hack 0.5.9 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "hex-literal-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro-hack 0.5.9 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "hmac" version = "0.7.0" @@ -3563,6 +3581,16 @@ dependencies = [ "toml 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "proc-macro-hack" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "proc-macro2" version = "0.4.20" @@ -3571,6 +3599,14 @@ dependencies = [ "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "proc-macro2" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "pulldown-cmark" version = "0.0.3" @@ -3623,6 +3659,14 @@ dependencies = [ "proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "quote" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "rand" version = "0.3.22" @@ -4302,6 +4346,16 @@ dependencies = [ "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "syn" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "synom" version = "0.11.3" @@ -4840,6 +4894,11 @@ name = "unicode-xid" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "unicode-xid" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "unreachable" version = "1.0.0" @@ -5288,6 +5347,8 @@ dependencies = [ "checksum hashmap_core 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "8e04cb7a5051270ef3fa79f8c7604d581ecfa73d520e74f554e45541c4b5881a" "checksum heapsize 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1679e6ea370dee694f91f1dc469bf94cf8f52051d147aec3e1f9497c6fc22461" "checksum heck 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ea04fa3ead4e05e51a7c806fc07271fdbde4e246a6c6d1efd52e72230b771b82" +"checksum hex-literal 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c3da68162fdd2147e66682e78e729bd77f93b4c99656db058c5782d8c6b6225a" +"checksum hex-literal-impl 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "06095d08c7c05760f11a071b3e1d4c5b723761c01bd8d7201c30a9536668a612" "checksum hmac 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f127a908633569f208325f86f71255d3363c79721d7f9fe31cd5569908819771" "checksum home 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "80dff82fb58cfbbc617fb9a9184b010be0529201553cda50ad04372bc2333aff" "checksum http 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)" = "eed324f0f0daf6ec10c474f150505af2c143f251722bf9dbd1261bd1f2ee2c1a" @@ -5410,12 +5471,15 @@ dependencies = [ "checksum primal-sieve 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)" = "da2d6ed369bb4b0273aeeb43f07c105c0117717cbae827b20719438eb2eb798c" "checksum primitive-types 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2288eb2a39386c4bc817974cc413afe173010dc80e470fcb1e9a35580869f024" "checksum proc-macro-crate 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "e10d4b51f154c8a7fb96fd6dad097cb74b863943ec010ac94b9fd1be8861fe1e" +"checksum proc-macro-hack 0.5.9 (registry+https://github.com/rust-lang/crates.io-index)" = "e688f31d92ffd7c1ddc57a1b4e6d773c0f2a14ee437a4b0a4f5a69c80eb221c8" "checksum proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)" = "3d7b7eaaa90b4a90a932a9ea6666c95a389e424eff347f0f793979289429feee" +"checksum proc-macro2 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "4c5c2380ae88876faae57698be9e9775e3544decad214599c3a6266cca6ac802" "checksum pulldown-cmark 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "8361e81576d2e02643b04950e487ec172b687180da65c731c03cf336784e6c07" "checksum pwasm-utils 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7e9135bed7b452e20dbb395a2d519abaf0c46d60e7ecc02daeeab447d29bada1" "checksum quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9274b940887ce9addde99c4eee6b5c44cc494b182b97e73dc8ffdcb3397fd3f0" "checksum quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6e920b65c65f10b2ae65c831a81a073a89edd28c7cce89475bff467ab4167a" "checksum quote 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)" = "dd636425967c33af890042c483632d33fa7a18f19ad1d7ea72e8998c6ef8dea5" +"checksum quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" "checksum rand 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)" = "15a732abf9d20f0ad8eeb6f909bf6868722d9a06e1e50802b6a70351f40b4eb1" "checksum rand 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "8356f47b32624fef5b3301c1be97e5944ecdd595409cc5da11d05f211db6cfbd" "checksum rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)" = "e464cd887e869cddcae8792a4ee31d23c7edd516700695608f5b98c67ee0131c" @@ -5489,6 +5553,7 @@ dependencies = [ "checksum subtle 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "01dca13cf6c3b179864ab3292bd794e757618d35a7766b7c46050c614ba00829" "checksum syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)" = "d3b891b9015c88c576343b9b3e41c2c11a51c219ef067b264bd9c8aa9b441dad" "checksum syn 0.15.26 (registry+https://github.com/rust-lang/crates.io-index)" = "f92e629aa1d9c827b2bb8297046c1ccffc57c99b947a680d3ccff1f136a3bee9" +"checksum syn 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "158521e6f544e7e3dcfc370ac180794aa38cb34a1b1e07609376d4adcf429b93" "checksum synom 0.11.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a393066ed9010ebaed60b9eafa373d4b1baac186dd7e008555b0f702b51945b6" "checksum synstructure 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "73687139bf99285483c96ac0add482c3776528beac1d97d444f6e91f203a2015" "checksum target_info 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c63f48baada5c52e65a29eef93ab4f8982681b67f9e8d29c7b05abcfec2b9ffe" @@ -5543,6 +5608,7 @@ dependencies = [ "checksum unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "882386231c45df4700b275c7ff55b6f3698780a650026380e72dabe76fa46526" "checksum unicode-xid 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f860d7d29cf02cb2f3f359fd35991af3d30bac52c57d265a3c461074cb4dc" "checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" +"checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" "checksum unreachable 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "382810877fe448991dfc7f0dd6e3ae5d58088fd0ea5e35189655f84e6814fa56" "checksum untrusted 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "55cd1f4b4e96b46aeb8d4855db4a7a9bd96eeeb5c6a1ab54593328761642ce2f" "checksum url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2a321979c09843d272956e73700d12c4e7d3d92b2ee112b31548aef0d4efc5a6" diff --git a/ethcore/engines/validator-set/src/safe_contract.rs b/ethcore/engines/validator-set/src/safe_contract.rs index d023802f0bf..666d43eac56 100644 --- a/ethcore/engines/validator-set/src/safe_contract.rs +++ b/ethcore/engines/validator-set/src/safe_contract.rs @@ -115,7 +115,7 @@ fn check_first_proof(machine: &Machine, contract_address: Address, old_header: H gas_limit: PROVIDED_GAS.into(), timestamp: old_header.timestamp(), last_hashes: { - // this will break if we don't inclue all 256 last hashes. + // this will break if we don't include all 256 last hashes. let mut last_hashes: Vec<_> = (0..256).map(|_| H256::zero()).collect(); last_hashes[255] = *old_header.parent_hash(); Arc::new(last_hashes) diff --git a/ethcore/evm/Cargo.toml b/ethcore/evm/Cargo.toml index 094d22f84d1..7c098654d76 100644 --- a/ethcore/evm/Cargo.toml +++ b/ethcore/evm/Cargo.toml @@ -19,6 +19,7 @@ memory-cache = { path = "../../util/memory-cache" } [dev-dependencies] rustc-hex = "1.0" criterion = "0.2" +hex-literal = "0.2.0" [features] evm-debug = [] diff --git a/ethcore/evm/src/factory.rs b/ethcore/evm/src/factory.rs index 7f441df013a..2b107e5a61f 100644 --- a/ethcore/evm/src/factory.rs +++ b/ethcore/evm/src/factory.rs @@ -47,7 +47,7 @@ impl Factory { /// for caching jump destinations. pub fn new(evm: VMType, cache_size: usize) -> Self { Factory { - evm: evm, + evm, evm_cache: Arc::new(SharedCache::new(cache_size)), } } diff --git a/ethcore/evm/src/instructions.rs b/ethcore/evm/src/instructions.rs index 0cdbb5687da..1580f7b591d 100644 --- a/ethcore/evm/src/instructions.rs +++ b/ethcore/evm/src/instructions.rs @@ -149,6 +149,8 @@ enum_with_from_u8! { DIFFICULTY = 0x44, #[doc = "get the block's gas limit"] GASLIMIT = 0x45, + #[doc = "get chain ID"] + CHAINID = 0x46, #[doc = "remove item from stack"] POP = 0x50, @@ -442,12 +444,7 @@ pub struct InstructionInfo { impl InstructionInfo { /// Create new instruction info. pub fn new(name: &'static str, args: usize, ret: usize, tier: GasPriceTier) -> Self { - InstructionInfo { - name: name, - args: args, - ret: ret, - tier: tier - } + InstructionInfo { name, args, ret, tier } } } @@ -504,6 +501,7 @@ lazy_static! { arr[NUMBER as usize] = Some(InstructionInfo::new("NUMBER", 0, 1, GasPriceTier::Base)); arr[DIFFICULTY as usize] = Some(InstructionInfo::new("DIFFICULTY", 0, 1, GasPriceTier::Base)); arr[GASLIMIT as usize] = Some(InstructionInfo::new("GASLIMIT", 0, 1, GasPriceTier::Base)); + arr[CHAINID as usize] = Some(InstructionInfo::new("CHAINID", 0, 1, GasPriceTier::Base)); arr[POP as usize] = Some(InstructionInfo::new("POP", 1, 0, GasPriceTier::Base)); arr[MLOAD as usize] = Some(InstructionInfo::new("MLOAD", 1, 1, GasPriceTier::VeryLow)); arr[MSTORE as usize] = Some(InstructionInfo::new("MSTORE", 2, 0, GasPriceTier::VeryLow)); diff --git a/ethcore/evm/src/interpreter/mod.rs b/ethcore/evm/src/interpreter/mod.rs index e8a318020de..85564385552 100644 --- a/ethcore/evm/src/interpreter/mod.rs +++ b/ethcore/evm/src/interpreter/mod.rs @@ -428,7 +428,8 @@ impl Interpreter { ((instruction == instructions::RETURNDATACOPY || instruction == instructions::RETURNDATASIZE) && !schedule.have_return_data) || (instruction == instructions::REVERT && !schedule.have_revert) || ((instruction == instructions::SHL || instruction == instructions::SHR || instruction == instructions::SAR) && !schedule.have_bitwise_shifting) || - (instruction == instructions::EXTCODEHASH && !schedule.have_extcodehash) + (instruction == instructions::EXTCODEHASH && !schedule.have_extcodehash) || + (instruction == instructions::CHAINID && !schedule.have_chain_id) { return Err(vm::Error::BadInstruction { instruction: instruction as u8 @@ -843,6 +844,9 @@ impl Interpreter { instructions::GASLIMIT => { self.stack.push(ext.env_info().gas_limit.clone()); }, + instructions::CHAINID => { + self.stack.push(ext.chain_id().into()) + }, // Stack instructions diff --git a/ethcore/evm/src/lib.rs b/ethcore/evm/src/lib.rs index 7cfa5a69eaa..db029d15f54 100644 --- a/ethcore/evm/src/lib.rs +++ b/ethcore/evm/src/lib.rs @@ -33,6 +33,8 @@ extern crate log; #[cfg(test)] extern crate rustc_hex; +#[cfg(test)] +extern crate hex_literal; pub mod evm; pub mod interpreter; diff --git a/ethcore/evm/src/tests.rs b/ethcore/evm/src/tests.rs index 15749b9266f..05a39e1b5a1 100644 --- a/ethcore/evm/src/tests.rs +++ b/ethcore/evm/src/tests.rs @@ -19,17 +19,22 @@ use std::str::FromStr; use std::hash::Hash; use std::sync::Arc; use std::collections::{HashMap, HashSet}; -use rustc_hex::FromHex; use ethereum_types::{U256, H256, Address}; use vm::{self, ActionParams, ActionValue, Ext}; use vm::tests::{FakeExt, FakeCall, FakeCallType, test_finalize}; use factory::Factory; use vmtype::VMType; +use hex_literal::hex; evm_test!{test_add: test_add_int} fn test_add(factory: super::Factory) { let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap(); - let code = "7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01600055".from_hex().unwrap(); + // 7f PUSH32 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff + // 7f PUSH32 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff + // 01 ADD + // 60 00 PUSH 0 + // 55 SSTORE + let code = hex!("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01600055").to_vec(); let mut params = ActionParams::default(); params.address = address.clone(); @@ -49,7 +54,12 @@ fn test_add(factory: super::Factory) { evm_test!{test_sha3: test_sha3_int} fn test_sha3(factory: super::Factory) { let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap(); - let code = "6000600020600055".from_hex().unwrap(); + // 60 00 PUSH 0 + // 60 00 PUSH 0 + // 20 SHA3 + // 60 00 PUSH 0 + // 55 SSTORE + let code = hex!("6000600020600055").to_vec(); let mut params = ActionParams::default(); params.address = address.clone(); @@ -69,7 +79,10 @@ fn test_sha3(factory: super::Factory) { evm_test!{test_address: test_address_int} fn test_address(factory: super::Factory) { let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap(); - let code = "30600055".from_hex().unwrap(); + // 30 ADDRESS + // 60 00 PUSH 0 + // 55 SSTORE + let code = hex!("30600055").to_vec(); let mut params = ActionParams::default(); params.address = address.clone(); @@ -90,7 +103,10 @@ evm_test!{test_origin: test_origin_int} fn test_origin(factory: super::Factory) { let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap(); let origin = Address::from_str("cd1722f2947def4cf144679da39c4c32bdc35681").unwrap(); - let code = "32600055".from_hex().unwrap(); + // 32 ORIGIN + // 60 00 PUSH 0 + // 55 SSTORE + let code = hex!("32600055").to_vec(); let mut params = ActionParams::default(); params.address = address.clone(); @@ -112,7 +128,10 @@ evm_test!{test_sender: test_sender_int} fn test_sender(factory: super::Factory) { let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap(); let sender = Address::from_str("cd1722f2947def4cf144679da39c4c32bdc35681").unwrap(); - let code = "33600055".from_hex().unwrap(); + // 33 CALLER + // 60 00 PUSH 0 + // 55 SSTORE + let code = hex!("33600055").to_vec(); let mut params = ActionParams::default(); params.address = address.clone(); @@ -130,6 +149,27 @@ fn test_sender(factory: super::Factory) { assert_store(&ext, 0, "000000000000000000000000cd1722f2947def4cf144679da39c4c32bdc35681"); } +evm_test!{test_chain_id: test_chain_id_int} +fn test_chain_id(factory: super::Factory) { + // 46 CHAINID + // 60 00 PUSH 0 + // 55 SSTORE + let code = hex!("46 60 00 55").to_vec(); + + let mut params = ActionParams::default(); + params.gas = U256::from(100_000); + params.code = Some(Arc::new(code)); + let mut ext = FakeExt::new_istanbul().with_chain_id(9); + + let gas_left = { + let vm = factory.create(params, ext.schedule(), ext.depth()); + test_finalize(vm.exec(&mut ext).ok().unwrap()).unwrap() + }; + + assert_eq!(gas_left, U256::from(79_995)); + assert_store(&ext, 0, "0000000000000000000000000000000000000000000000000000000000000009"); +} + evm_test!{test_extcodecopy: test_extcodecopy_int} fn test_extcodecopy(factory: super::Factory) { // 33 - sender @@ -145,8 +185,8 @@ fn test_extcodecopy(factory: super::Factory) { let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap(); let sender = Address::from_str("cd1722f2947def4cf144679da39c4c32bdc35681").unwrap(); - let code = "333b60006000333c600051600055".from_hex().unwrap(); - let sender_code = "6005600055".from_hex().unwrap(); + let code = hex!("333b60006000333c600051600055").to_vec(); + let sender_code = hex!("6005600055").to_vec(); let mut params = ActionParams::default(); params.address = address.clone(); @@ -168,7 +208,7 @@ fn test_extcodecopy(factory: super::Factory) { evm_test!{test_log_empty: test_log_empty_int} fn test_log_empty(factory: super::Factory) { let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap(); - let code = "60006000a0".from_hex().unwrap(); + let code = hex!("60006000a0").to_vec(); let mut params = ActionParams::default(); params.address = address.clone(); @@ -199,7 +239,7 @@ fn test_log_sender(factory: super::Factory) { let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap(); let sender = Address::from_str("cd1722f3947def4cf144679da39c4c32bdc35681").unwrap(); - let code = "60ff6000533360206000a1".from_hex().unwrap(); + let code = hex!("60ff6000533360206000a1").to_vec(); let mut params = ActionParams::default(); params.address = address.clone(); @@ -217,13 +257,13 @@ fn test_log_sender(factory: super::Factory) { assert_eq!(ext.logs.len(), 1); assert_eq!(ext.logs[0].topics.len(), 1); assert_eq!(ext.logs[0].topics[0], H256::from_str("000000000000000000000000cd1722f3947def4cf144679da39c4c32bdc35681").unwrap()); - assert_eq!(ext.logs[0].data, "ff00000000000000000000000000000000000000000000000000000000000000".from_hex().unwrap()); + assert_eq!(ext.logs[0].data, hex!("ff00000000000000000000000000000000000000000000000000000000000000").to_vec()); } evm_test!{test_blockhash: test_blockhash_int} fn test_blockhash(factory: super::Factory) { let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap(); - let code = "600040600055".from_hex().unwrap(); + let code = hex!("600040600055").to_vec(); let blockhash = H256::from_str("123400000000000000000000cd1722f2947def4cf144679da39c4c32bdc35681").unwrap(); let mut params = ActionParams::default(); @@ -245,8 +285,8 @@ fn test_blockhash(factory: super::Factory) { evm_test!{test_calldataload: test_calldataload_int} fn test_calldataload(factory: super::Factory) { let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap(); - let code = "600135600055".from_hex().unwrap(); - let data = "0123ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff23".from_hex().unwrap(); + let code = hex!("600135600055").to_vec(); + let data = hex!("0123ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff23").to_vec(); let mut params = ActionParams::default(); params.address = address.clone(); @@ -267,7 +307,7 @@ fn test_calldataload(factory: super::Factory) { evm_test!{test_author: test_author_int} fn test_author(factory: super::Factory) { let author = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap(); - let code = "41600055".from_hex().unwrap(); + let code = hex!("41600055").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -287,7 +327,7 @@ fn test_author(factory: super::Factory) { evm_test!{test_timestamp: test_timestamp_int} fn test_timestamp(factory: super::Factory) { let timestamp = 0x1234; - let code = "42600055".from_hex().unwrap(); + let code = hex!("42600055").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -307,7 +347,7 @@ fn test_timestamp(factory: super::Factory) { evm_test!{test_number: test_number_int} fn test_number(factory: super::Factory) { let number = 0x1234; - let code = "43600055".from_hex().unwrap(); + let code = hex!("43600055").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -327,7 +367,7 @@ fn test_number(factory: super::Factory) { evm_test!{test_difficulty: test_difficulty_int} fn test_difficulty(factory: super::Factory) { let difficulty = U256::from(0x1234); - let code = "44600055".from_hex().unwrap(); + let code = hex!("44600055").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -347,7 +387,7 @@ fn test_difficulty(factory: super::Factory) { evm_test!{test_gas_limit: test_gas_limit_int} fn test_gas_limit(factory: super::Factory) { let gas_limit = U256::from(0x1234); - let code = "45600055".from_hex().unwrap(); + let code = hex!("45600055").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -366,7 +406,7 @@ fn test_gas_limit(factory: super::Factory) { evm_test!{test_mul: test_mul_int} fn test_mul(factory: super::Factory) { - let code = "65012365124623626543219002600055".from_hex().unwrap(); + let code = hex!("65012365124623626543219002600055").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -384,7 +424,7 @@ fn test_mul(factory: super::Factory) { evm_test!{test_sub: test_sub_int} fn test_sub(factory: super::Factory) { - let code = "65012365124623626543219003600055".from_hex().unwrap(); + let code = hex!("65012365124623626543219003600055").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -402,7 +442,7 @@ fn test_sub(factory: super::Factory) { evm_test!{test_div: test_div_int} fn test_div(factory: super::Factory) { - let code = "65012365124623626543219004600055".from_hex().unwrap(); + let code = hex!("65012365124623626543219004600055").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -420,7 +460,7 @@ fn test_div(factory: super::Factory) { evm_test!{test_div_zero: test_div_zero_int} fn test_div_zero(factory: super::Factory) { - let code = "6501236512462360009004600055".from_hex().unwrap(); + let code = hex!("6501236512462360009004600055").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -438,7 +478,7 @@ fn test_div_zero(factory: super::Factory) { evm_test!{test_mod: test_mod_int} fn test_mod(factory: super::Factory) { - let code = "650123651246236265432290066000556501236512462360009006600155".from_hex().unwrap(); + let code = hex!("650123651246236265432290066000556501236512462360009006600155").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -457,7 +497,7 @@ fn test_mod(factory: super::Factory) { evm_test!{test_smod: test_smod_int} fn test_smod(factory: super::Factory) { - let code = "650123651246236265432290076000556501236512462360009007600155".from_hex().unwrap(); + let code = hex!("650123651246236265432290076000556501236512462360009007600155").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -476,7 +516,7 @@ fn test_smod(factory: super::Factory) { evm_test!{test_sdiv: test_sdiv_int} fn test_sdiv(factory: super::Factory) { - let code = "650123651246236265432290056000556501236512462360009005600155".from_hex().unwrap(); + let code = hex!("650123651246236265432290056000556501236512462360009005600155").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -495,7 +535,7 @@ fn test_sdiv(factory: super::Factory) { evm_test!{test_exp: test_exp_int} fn test_exp(factory: super::Factory) { - let code = "6016650123651246230a6000556001650123651246230a6001556000650123651246230a600255".from_hex().unwrap(); + let code = hex!("6016650123651246230a6000556001650123651246230a6001556000650123651246230a600255").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -515,7 +555,7 @@ fn test_exp(factory: super::Factory) { evm_test!{test_comparison: test_comparison_int} fn test_comparison(factory: super::Factory) { - let code = "601665012365124623818181811060005511600155146002556415235412358014600355".from_hex().unwrap(); + let code = hex!("601665012365124623818181811060005511600155146002556415235412358014600355").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -536,7 +576,7 @@ fn test_comparison(factory: super::Factory) { evm_test!{test_signed_comparison: test_signed_comparison_int} fn test_signed_comparison(factory: super::Factory) { - let code = "60106000036010818112600055136001556010601060000381811260025513600355".from_hex().unwrap(); + let code = hex!("60106000036010818112600055136001556010601060000381811260025513600355").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -557,7 +597,7 @@ fn test_signed_comparison(factory: super::Factory) { evm_test!{test_bitops: test_bitops_int} fn test_bitops(factory: super::Factory) { - let code = "60ff610ff08181818116600055176001551860025560008015600355198015600455600555".from_hex().unwrap(); + let code = hex!("60ff610ff08181818116600055176001551860025560008015600355198015600455600555").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(150_000); @@ -580,7 +620,7 @@ fn test_bitops(factory: super::Factory) { evm_test!{test_addmod_mulmod: test_addmod_mulmod_int} fn test_addmod_mulmod(factory: super::Factory) { - let code = "60ff60f060108282820860005509600155600060f0601082828208196002550919600355".from_hex().unwrap(); + let code = hex!("60ff60f060108282820860005509600155600060f0601082828208196002550919600355").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -601,7 +641,7 @@ fn test_addmod_mulmod(factory: super::Factory) { evm_test!{test_byte: test_byte_int} fn test_byte(factory: super::Factory) { - let code = "60f061ffff1a600055610fff601f1a600155".from_hex().unwrap(); + let code = hex!("60f061ffff1a600055610fff601f1a600155").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -620,7 +660,7 @@ fn test_byte(factory: super::Factory) { evm_test!{test_signextend: test_signextend_int} fn test_signextend(factory: super::Factory) { - let code = "610fff60020b60005560ff60200b600155".from_hex().unwrap(); + let code = hex!("610fff60020b60005560ff60200b600155").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -640,7 +680,7 @@ fn test_signextend(factory: super::Factory) { #[test] // JIT just returns out of gas fn test_badinstruction_int() { let factory = super::Factory::new(VMType::Interpreter, 1024 * 32); - let code = "af".from_hex().unwrap(); + let code = hex!("af").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -660,7 +700,7 @@ fn test_badinstruction_int() { evm_test!{test_pop: test_pop_int} fn test_pop(factory: super::Factory) { - let code = "60f060aa50600055".from_hex().unwrap(); + let code = hex!("60f060aa50600055").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(100_000); @@ -678,7 +718,7 @@ fn test_pop(factory: super::Factory) { evm_test!{test_extops: test_extops_int} fn test_extops(factory: super::Factory) { - let code = "5a6001555836553a600255386003553460045560016001526016590454600555".from_hex().unwrap(); + let code = hex!("5a6001555836553a600255386003553460045560016001526016590454600555").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(150_000); @@ -703,7 +743,7 @@ fn test_extops(factory: super::Factory) { evm_test!{test_jumps: test_jumps_int} fn test_jumps(factory: super::Factory) { - let code = "600160015560066000555b60016000540380806000551560245760015402600155600a565b".from_hex().unwrap(); + let code = hex!("600160015560066000555b60016000540380806000551560245760015402600155600a565b").to_vec(); let mut params = ActionParams::default(); params.gas = U256::from(150_000); @@ -723,7 +763,7 @@ fn test_jumps(factory: super::Factory) { evm_test!{test_calls: test_calls_int} fn test_calls(factory: super::Factory) { - let code = "600054602d57600160005560006000600060006050610998610100f160006000600060006050610998610100f25b".from_hex().unwrap(); + let code = hex!("600054602d57600160005560006000600060006050610998610100f160006000600060006050610998610100f25b").to_vec(); let address = Address::from_low_u64_be(0x155); let code_address = Address::from_low_u64_be(0x998); @@ -769,7 +809,7 @@ fn test_calls(factory: super::Factory) { evm_test!{test_create_in_staticcall: test_create_in_staticcall_int} fn test_create_in_staticcall(factory: super::Factory) { - let code = "600060006064f000".from_hex().unwrap(); + let code = hex!("600060006064f000").to_vec(); let address = Address::from_low_u64_be(0x155); let mut params = ActionParams::default(); @@ -793,68 +833,68 @@ fn test_shl(factory: super::Factory) { push_two_pop_one_constantinople_test( &factory, 0x1b, - "0000000000000000000000000000000000000000000000000000000000000001", - "00", + hex!("0000000000000000000000000000000000000000000000000000000000000001").to_vec(), + hex!("00").to_vec(), "0000000000000000000000000000000000000000000000000000000000000001"); push_two_pop_one_constantinople_test( &factory, 0x1b, - "0000000000000000000000000000000000000000000000000000000000000001", - "01", + hex!("0000000000000000000000000000000000000000000000000000000000000001").to_vec(), + hex!("01").to_vec(), "0000000000000000000000000000000000000000000000000000000000000002"); push_two_pop_one_constantinople_test( &factory, 0x1b, - "0000000000000000000000000000000000000000000000000000000000000001", - "ff", + hex!("0000000000000000000000000000000000000000000000000000000000000001").to_vec(), + hex!("ff").to_vec(), "8000000000000000000000000000000000000000000000000000000000000000"); push_two_pop_one_constantinople_test( &factory, 0x1b, - "0000000000000000000000000000000000000000000000000000000000000001", - "0100", + hex!("0000000000000000000000000000000000000000000000000000000000000001").to_vec(), + hex!("0100").to_vec(), "0000000000000000000000000000000000000000000000000000000000000000"); push_two_pop_one_constantinople_test( &factory, 0x1b, - "0000000000000000000000000000000000000000000000000000000000000001", - "0101", + hex!("0000000000000000000000000000000000000000000000000000000000000001").to_vec(), + hex!("0101").to_vec(), "0000000000000000000000000000000000000000000000000000000000000000"); push_two_pop_one_constantinople_test( &factory, 0x1b, - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "00", + hex!("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("00").to_vec(), "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); push_two_pop_one_constantinople_test( &factory, 0x1b, - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "01", + hex!("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("01").to_vec(), "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"); push_two_pop_one_constantinople_test( &factory, 0x1b, - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "ff", + hex!("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("ff").to_vec(), "8000000000000000000000000000000000000000000000000000000000000000"); push_two_pop_one_constantinople_test( &factory, 0x1b, - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "0100", + hex!("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("0100").to_vec(), "0000000000000000000000000000000000000000000000000000000000000000"); push_two_pop_one_constantinople_test( &factory, 0x1b, - "0000000000000000000000000000000000000000000000000000000000000000", - "01", + hex!("0000000000000000000000000000000000000000000000000000000000000000").to_vec(), + hex!("01").to_vec(), "0000000000000000000000000000000000000000000000000000000000000000"); push_two_pop_one_constantinople_test( &factory, 0x1b, - "7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "01", + hex!("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("01").to_vec(), "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"); } @@ -863,68 +903,68 @@ fn test_shr(factory: super::Factory) { push_two_pop_one_constantinople_test( &factory, 0x1c, - "0000000000000000000000000000000000000000000000000000000000000001", - "00", + hex!("0000000000000000000000000000000000000000000000000000000000000001").to_vec(), + hex!("00").to_vec(), "0000000000000000000000000000000000000000000000000000000000000001"); push_two_pop_one_constantinople_test( &factory, 0x1c, - "0000000000000000000000000000000000000000000000000000000000000001", - "01", + hex!("0000000000000000000000000000000000000000000000000000000000000001").to_vec(), + hex!("01").to_vec(), "0000000000000000000000000000000000000000000000000000000000000000"); push_two_pop_one_constantinople_test( &factory, 0x1c, - "8000000000000000000000000000000000000000000000000000000000000000", - "01", + hex!("8000000000000000000000000000000000000000000000000000000000000000").to_vec(), + hex!("01").to_vec(), "4000000000000000000000000000000000000000000000000000000000000000"); push_two_pop_one_constantinople_test( &factory, 0x1c, - "8000000000000000000000000000000000000000000000000000000000000000", - "ff", + hex!("8000000000000000000000000000000000000000000000000000000000000000").to_vec(), + hex!("ff").to_vec(), "0000000000000000000000000000000000000000000000000000000000000001"); push_two_pop_one_constantinople_test( &factory, 0x1c, - "8000000000000000000000000000000000000000000000000000000000000000", - "0100", + hex!("8000000000000000000000000000000000000000000000000000000000000000").to_vec(), + hex!("0100").to_vec(), "0000000000000000000000000000000000000000000000000000000000000000"); push_two_pop_one_constantinople_test( &factory, 0x1c, - "8000000000000000000000000000000000000000000000000000000000000000", - "0101", + hex!("8000000000000000000000000000000000000000000000000000000000000000").to_vec(), + hex!("0101").to_vec(), "0000000000000000000000000000000000000000000000000000000000000000"); push_two_pop_one_constantinople_test( &factory, 0x1c, - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "00", + hex!("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("00").to_vec(), "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); push_two_pop_one_constantinople_test( &factory, 0x1c, - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "01", + hex!("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("01").to_vec(), "7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); push_two_pop_one_constantinople_test( &factory, 0x1c, - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "ff", + hex!("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("ff").to_vec(), "0000000000000000000000000000000000000000000000000000000000000001"); push_two_pop_one_constantinople_test( &factory, 0x1c, - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "0100", + hex!("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("0100").to_vec(), "0000000000000000000000000000000000000000000000000000000000000000"); push_two_pop_one_constantinople_test( &factory, 0x1c, - "0000000000000000000000000000000000000000000000000000000000000000", - "01", + hex!("0000000000000000000000000000000000000000000000000000000000000000").to_vec(), + hex!("01").to_vec(), "0000000000000000000000000000000000000000000000000000000000000000"); } @@ -933,104 +973,102 @@ fn test_sar(factory: super::Factory) { push_two_pop_one_constantinople_test( &factory, 0x1d, - "0000000000000000000000000000000000000000000000000000000000000001", - "00", + hex!("0000000000000000000000000000000000000000000000000000000000000001").to_vec(), + hex!("00").to_vec(), "0000000000000000000000000000000000000000000000000000000000000001"); push_two_pop_one_constantinople_test( &factory, 0x1d, - "0000000000000000000000000000000000000000000000000000000000000001", - "01", + hex!("0000000000000000000000000000000000000000000000000000000000000001").to_vec(), + hex!("01").to_vec(), "0000000000000000000000000000000000000000000000000000000000000000"); push_two_pop_one_constantinople_test( &factory, 0x1d, - "8000000000000000000000000000000000000000000000000000000000000000", - "01", + hex!("8000000000000000000000000000000000000000000000000000000000000000").to_vec(), + hex!("01").to_vec(), "c000000000000000000000000000000000000000000000000000000000000000"); push_two_pop_one_constantinople_test( &factory, 0x1d, - "8000000000000000000000000000000000000000000000000000000000000000", - "ff", + hex!("8000000000000000000000000000000000000000000000000000000000000000").to_vec(), + hex!("ff").to_vec(), "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); push_two_pop_one_constantinople_test( &factory, 0x1d, - "8000000000000000000000000000000000000000000000000000000000000000", - "0100", + hex!("8000000000000000000000000000000000000000000000000000000000000000").to_vec(), + hex!("0100").to_vec(), "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); push_two_pop_one_constantinople_test( &factory, 0x1d, - "8000000000000000000000000000000000000000000000000000000000000000", - "0101", + hex!("8000000000000000000000000000000000000000000000000000000000000000").to_vec(), + hex!("0101").to_vec(), "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); push_two_pop_one_constantinople_test( &factory, 0x1d, - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "00", + hex!("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("00").to_vec(), "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); push_two_pop_one_constantinople_test( &factory, 0x1d, - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "01", + hex!("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("01").to_vec(), "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); push_two_pop_one_constantinople_test( &factory, 0x1d, - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "ff", + hex!("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("ff").to_vec(), "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); push_two_pop_one_constantinople_test( &factory, 0x1d, - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "0100", + hex!("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("0100").to_vec(), "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); push_two_pop_one_constantinople_test( &factory, 0x1d, - "0000000000000000000000000000000000000000000000000000000000000000", - "01", + hex!("0000000000000000000000000000000000000000000000000000000000000000").to_vec(), + hex!("01").to_vec(), "0000000000000000000000000000000000000000000000000000000000000000"); push_two_pop_one_constantinople_test( &factory, 0x1d, - "4000000000000000000000000000000000000000000000000000000000000000", - "fe", + hex!("4000000000000000000000000000000000000000000000000000000000000000").to_vec(), + hex!("fe").to_vec(), "0000000000000000000000000000000000000000000000000000000000000001"); push_two_pop_one_constantinople_test( &factory, 0x1d, - "7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "f8", + hex!("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("f8").to_vec(), "000000000000000000000000000000000000000000000000000000000000007f"); push_two_pop_one_constantinople_test( &factory, 0x1d, - "7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "fe", + hex!("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("fe").to_vec(), "0000000000000000000000000000000000000000000000000000000000000001"); push_two_pop_one_constantinople_test( &factory, 0x1d, - "7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "ff", + hex!("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("ff").to_vec(), "0000000000000000000000000000000000000000000000000000000000000000"); push_two_pop_one_constantinople_test( &factory, 0x1d, - "7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "0100", + hex!("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").to_vec(), + hex!("0100").to_vec(), "0000000000000000000000000000000000000000000000000000000000000000"); } -fn push_two_pop_one_constantinople_test(factory: &super::Factory, opcode: u8, push1: &str, push2: &str, result: &str) { - let mut push1 = push1.from_hex().unwrap(); - let mut push2 = push2.from_hex().unwrap(); +fn push_two_pop_one_constantinople_test(factory: &super::Factory, opcode: u8, mut push1: Vec, mut push2: Vec, result: &str) { assert!(push1.len() <= 32 && push1.len() != 0); assert!(push2.len() <= 32 && push2.len() != 0); diff --git a/ethcore/machine/src/externalities.rs b/ethcore/machine/src/externalities.rs index d002f07bea1..b951eba16fa 100644 --- a/ethcore/machine/src/externalities.rs +++ b/ethcore/machine/src/externalities.rs @@ -416,6 +416,10 @@ impl<'a, T: 'a, V: 'a, B: 'a> Ext for Externalities<'a, T, V, B> self.env_info } + fn chain_id(&self) -> u64 { + self.machine.params().chain_id + } + fn depth(&self) -> usize { self.depth } diff --git a/ethcore/src/json_tests/executive.rs b/ethcore/src/json_tests/executive.rs index 514206fdd5c..2ce13f6f0aa 100644 --- a/ethcore/src/json_tests/executive.rs +++ b/ethcore/src/json_tests/executive.rs @@ -216,6 +216,8 @@ impl<'a, T: 'a, V: 'a, B: 'a> Ext for TestExt<'a, T, V, B> self.ext.env_info() } + fn chain_id(&self) -> u64 { 0 } + fn depth(&self) -> usize { 0 } diff --git a/ethcore/types/src/engines/params.rs b/ethcore/types/src/engines/params.rs index 4b6fba31dbc..fc8eb96674c 100644 --- a/ethcore/types/src/engines/params.rs +++ b/ethcore/types/src/engines/params.rs @@ -90,6 +90,8 @@ pub struct CommonParams { pub eip1283_disable_transition: BlockNumber, /// Number of first block where EIP-1014 rules begin. pub eip1014_transition: BlockNumber, + /// Number of first block where EIP-1344 rules begin: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1344.md + pub eip1344_transition: BlockNumber, /// Number of first block where EIP-2028 rules begin. pub eip2028_transition: BlockNumber, /// Number of first block where dust cleanup rules (EIP-168 and EIP169) begin. @@ -161,6 +163,7 @@ impl CommonParams { schedule.have_return_data = block_number >= self.eip211_transition; schedule.have_bitwise_shifting = block_number >= self.eip145_transition; schedule.have_extcodehash = block_number >= self.eip1052_transition; + schedule.have_chain_id = block_number >= self.eip1344_transition; schedule.eip1283 = block_number >= self.eip1283_transition && !(block_number >= self.eip1283_disable_transition); if block_number >= self.eip2028_transition { schedule.tx_data_non_zero_gas = 16; @@ -282,6 +285,10 @@ impl From for CommonParams { BlockNumber::max_value, Into::into, ), + eip1344_transition: p.eip1344_transition.map_or_else( + BlockNumber::max_value, + Into::into, + ), eip2028_transition: p.eip2028_transition.map_or_else( BlockNumber::max_value, Into::into, diff --git a/ethcore/vm/src/env_info.rs b/ethcore/vm/src/env_info.rs index 6c602d80fe6..6dc742938fe 100644 --- a/ethcore/vm/src/env_info.rs +++ b/ethcore/vm/src/env_info.rs @@ -65,7 +65,7 @@ impl From for EnvInfo { fn from(e: ethjson::vm::Env) -> Self { let number = e.number.into(); EnvInfo { - number: number, + number, author: e.author.into(), difficulty: e.difficulty.into(), gas_limit: e.gas_limit.into(), diff --git a/ethcore/vm/src/ext.rs b/ethcore/vm/src/ext.rs index ba684958977..63d9595fb0a 100644 --- a/ethcore/vm/src/ext.rs +++ b/ethcore/vm/src/ext.rs @@ -145,6 +145,9 @@ pub trait Ext { /// Returns environment info. fn env_info(&self) -> &EnvInfo; + /// Returns the chain ID of the blockchain + fn chain_id(&self) -> u64; + /// Returns current depth of execution. /// /// If contract A calls contract B, and contract B calls C, diff --git a/ethcore/vm/src/schedule.rs b/ethcore/vm/src/schedule.rs index 66c2391ac5b..e11603ecdaa 100644 --- a/ethcore/vm/src/schedule.rs +++ b/ethcore/vm/src/schedule.rs @@ -122,6 +122,8 @@ pub struct Schedule { pub have_return_data: bool, /// SHL, SHR, SAR opcodes enabled. pub have_bitwise_shifting: bool, + /// CHAINID opcode enabled. + pub have_chain_id: bool, /// Kill basic accounts below this balance if touched. pub kill_dust: CleanDustMode, /// Enable EIP-1283 rules @@ -220,6 +222,7 @@ impl Schedule { have_revert: false, have_return_data: false, have_bitwise_shifting: false, + have_chain_id: false, have_extcodehash: false, stack_limit: 1024, max_depth: 1024, @@ -291,6 +294,7 @@ impl Schedule { /// Schedule for the Istanbul fork of the Ethereum main net. pub fn new_istanbul() -> Schedule { let mut schedule = Self::new_constantinople(); + schedule.have_chain_id = true; schedule.tx_data_non_zero_gas = 16; schedule } @@ -303,6 +307,7 @@ impl Schedule { have_revert: false, have_return_data: false, have_bitwise_shifting: false, + have_chain_id: false, have_extcodehash: false, stack_limit: 1024, max_depth: 1024, diff --git a/ethcore/vm/src/tests.rs b/ethcore/vm/src/tests.rs index b6709d6efff..40ae0dac455 100644 --- a/ethcore/vm/src/tests.rs +++ b/ethcore/vm/src/tests.rs @@ -67,6 +67,8 @@ pub struct FakeExt { pub balances: HashMap, pub tracing: bool, pub is_static: bool, + + chain_id: u64, } // similar to the normal `finalize` function, but ignoring NeedsReturn. @@ -98,7 +100,7 @@ impl FakeExt { ext } - /// New fake externalities with constantinople schedule rules + /// New fake externalities with Istanbul schedule rules pub fn new_istanbul() -> Self { let mut ext = FakeExt::default(); ext.schedule = Schedule::new_istanbul(); @@ -110,6 +112,12 @@ impl FakeExt { self.schedule.wasm = Some(Default::default()); self } + + /// Set chain ID + pub fn with_chain_id(mut self, chain_id: u64) -> Self { + self.chain_id = chain_id; + self + } } impl Ext for FakeExt { @@ -208,7 +216,7 @@ impl Ext for FakeExt { fn log(&mut self, topics: Vec, data: &[u8]) -> Result<()> { self.logs.push(FakeLogEntry { - topics: topics, + topics, data: data.to_vec() }); Ok(()) @@ -231,6 +239,10 @@ impl Ext for FakeExt { &self.info } + fn chain_id(&self) -> u64 { + self.chain_id + } + fn depth(&self) -> usize { self.depth } diff --git a/json/src/spec/params.rs b/json/src/spec/params.rs index 68093db20c6..29c842b87bb 100644 --- a/json/src/spec/params.rs +++ b/json/src/spec/params.rs @@ -94,6 +94,8 @@ pub struct Params { /// See `CommonParams` docs. pub eip1014_transition: Option, /// See `CommonParams` docs. + pub eip1344_transition: Option, + /// See `CommonParams` docs. pub eip2028_transition: Option, /// See `CommonParams` docs. pub dust_protection_transition: Option, diff --git a/parity/informant.rs b/parity/informant.rs index 60ba59f7beb..e4511aff483 100644 --- a/parity/informant.rs +++ b/parity/informant.rs @@ -24,7 +24,7 @@ use std::time::{Instant, Duration}; use atty; use ethcore::client::{ChainNotify, NewBlocks, Client}; -use client_traits::{BlockInfo, ChainInfo, BlockChainClient, IoClient}; +use client_traits::{BlockInfo, ChainInfo, BlockChainClient}; use types::{ BlockNumber, client_types::ClientReport, diff --git a/rpc/Cargo.toml b/rpc/Cargo.toml index ff8fa932515..27b2b6fda47 100644 --- a/rpc/Cargo.toml +++ b/rpc/Cargo.toml @@ -67,7 +67,6 @@ account-state = { path = "../ethcore/account-state" } stats = { path = "../util/stats" } trace = { path = "../ethcore/trace" } vm = { path = "../ethcore/vm" } -verification = { path = "../ethcore/verification" } [dev-dependencies] client-traits = { path = "../ethcore/client-traits" } @@ -80,6 +79,7 @@ macros = { path = "../util/macros" } spec = { path = "../ethcore/spec" } pretty_assertions = "0.1" transaction-pool = "2.0" +verification = { path = "../ethcore/verification" } [features] accounts = ["ethcore-accounts"] diff --git a/rpc/src/lib.rs b/rpc/src/lib.rs index 5bff9358294..5cb96fa1f14 100644 --- a/rpc/src/lib.rs +++ b/rpc/src/lib.rs @@ -89,7 +89,6 @@ extern crate account_state; extern crate stats; extern crate tempdir; extern crate trace; -extern crate verification; extern crate vm; #[cfg(any(test, feature = "ethcore-accounts"))] @@ -130,6 +129,8 @@ extern crate ethcore_io as io; #[cfg(test)] extern crate spec; +#[cfg(test)] +extern crate verification; pub extern crate jsonrpc_ws_server as ws; From 4f12d7ad121deb390e81f0310c8dcc383a00cdde Mon Sep 17 00:00:00 2001 From: Andronik Ordian Date: Wed, 28 Aug 2019 18:24:06 +0200 Subject: [PATCH 5/7] [trace] check mem diff within range (#11002) --- ethcore/trace/src/executive_tracer.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/ethcore/trace/src/executive_tracer.rs b/ethcore/trace/src/executive_tracer.rs index 6ece943fd96..23739a34cc2 100644 --- a/ethcore/trace/src/executive_tracer.rs +++ b/ethcore/trace/src/executive_tracer.rs @@ -18,7 +18,7 @@ use ethereum_types::{U256, Address}; use vm::{Error as VmError, ActionParams}; -use log::debug; +use log::{debug, warn}; use crate::{ Tracer, VMTracer, FlatTrace, trace::{Call, Create, Action, Res, CreateResult, CallResult, VMTrace, VMOperation, VMExecutedOperation, MemoryDiff, StorageDiff, Suicide, Reward, RewardType}, @@ -248,7 +248,19 @@ impl VMTracer for ExecutiveVMTracer { } fn trace_executed(&mut self, gas_used: U256, stack_push: &[U256], mem: &[u8]) { - let mem_diff = self.last_mem_written.take().map(|(o, s)| (o, &(mem[o..o+s]))); + let mem_diff = self.last_mem_written.take().map(|(o, s)| { + if o + s > mem.len() { + warn!( + target: "trace", + "Last mem written is out of bounds {} (mem is {})", + o + s, + mem.len(), + ); + (o, &[][..]) + } else { + (o, &(mem[o..o+s])) + } + }); let store_diff = self.last_store_written.take(); Self::with_trace_in_depth(&mut self.data, self.depth, move |trace| { let ex = VMExecutedOperation { From 3420c2bac08353f4269b9589decf8a9351275e64 Mon Sep 17 00:00:00 2001 From: phahulin Date: Thu, 29 Aug 2019 10:33:33 +0300 Subject: [PATCH 6/7] xDai chain support and nodes list update (#10989) * Update bootnodes list for known networks * Add XDai chain * Rename xdai chain in config * Fix missing comma --- ethcore/res/ethereum/kovan.json | 2 + ethcore/res/ethereum/poacore.json | 1 - ethcore/res/ethereum/poasokol.json | 2 +- ethcore/res/ethereum/xdai.json | 152 +++++++++++++++++++++++++++++ ethcore/spec/src/chain.rs | 1 + parity/cli/mod.rs | 2 +- parity/params.rs | 6 ++ 7 files changed, 163 insertions(+), 3 deletions(-) create mode 100644 ethcore/res/ethereum/xdai.json diff --git a/ethcore/res/ethereum/kovan.json b/ethcore/res/ethereum/kovan.json index 67da802a951..2afd6e433ed 100644 --- a/ethcore/res/ethereum/kovan.json +++ b/ethcore/res/ethereum/kovan.json @@ -5382,6 +5382,8 @@ }, "nodes": [ "enode://f6e37b943bad3a78cb8589b1798d30d210ffd39cfcd2c8f2de4f098467fd49c667980100d919da7ca46cd50505d30989abda87f0b9339377de13d6592c22caf8@34.198.49.72:30303", + "enode://16898006ba2cd4fa8bf9a3dfe32684c178fa861df144bfc21fe800dc4838a03e342056951fa9fd533dcb0be1219e306106442ff2cf1f7e9f8faa5f2fc1a3aa45@116.203.116.241:30303", + "enode://2909846f78c37510cc0e306f185323b83bb2209e5ff4fdd279d93c60e3f365e3c6e62ad1d2133ff11f9fd6d23ad9c3dad73bb974d53a22f7d1ac5b7dea79d0b0@3.217.96.11:30303", "enode://56abaf065581a5985b8c5f4f88bd202526482761ba10be9bfdcd14846dd01f652ec33fde0f8c0fd1db19b59a4c04465681fcef50e11380ca88d25996191c52de@40.71.221.215:30303", "enode://d07827483dc47b368eaf88454fb04b41b7452cf454e194e2bd4c14f98a3278fed5d819dbecd0d010407fc7688d941ee1e58d4f9c6354d3da3be92f55c17d7ce3@52.166.117.77:30303", "enode://38e6e7fd416293ed120d567a2675fe078c0205ab0671abf16982ce969823bd1f3443d590c18b321dfae7dcbe1f6ba98ef8702f255c3c9822a188abb82c53adca@51.77.66.187:30303", diff --git a/ethcore/res/ethereum/poacore.json b/ethcore/res/ethereum/poacore.json index a4fdbcbf10f..d1e0581ae59 100644 --- a/ethcore/res/ethereum/poacore.json +++ b/ethcore/res/ethereum/poacore.json @@ -51,7 +51,6 @@ }, "nodes": [ "enode://6e3d1b39cbd2a9c4f053a27e68fd90d0bac83691dfdc4a13c59f2555078a71e63c5daaee5a82aa6db500512760a5456f86076bf8bbe8011c27c82ed7d6f5fb26@45.77.140.210:30303", - "enode://f4698ad485a027497e1cc992bb5f7cecee2b32a44c47202738d8d0eecfab719541988d0cbcbc5ea94c6c959e5cddeb85fc6ae75fb63dc3bf87cdbe9e6f615e9d@206.156.242.64:30303", "enode://31dffed97f8fed1f34fe66453280a89cbeeda60cf28f6fbb212ebbefd7c7566a02c1c7d5c00bbbb49b9fa8a49f157e0f786f379ca9bcbf2fea24de70d70a22b6@206.156.242.61:30303", "enode://6bdc7553ab2e4914cb47774c1e6d8c8f47ac7c3981891f85f65d06f208ea1bc4d3bf982b330950e0a0cd127efd7145c4df7113159a1d4a06ed722e6c16d0ac6c@45.32.215.190:30303", "enode://872d82a24144bc007658fb6fac0dcdfb9b63aeb05ef563a06d0186f2d1e5ffbfc5c4f1244891a8a86ef70682b9d24382e654b305224883698862e2df647a4d23@45.76.236.247:30303", diff --git a/ethcore/res/ethereum/poasokol.json b/ethcore/res/ethereum/poasokol.json index 8ee91c90c06..c20b6a0817c 100644 --- a/ethcore/res/ethereum/poasokol.json +++ b/ethcore/res/ethereum/poasokol.json @@ -58,7 +58,7 @@ "enode://8e0af07c86ec36590bb6368e7ad0c45b6dc658f5fb66ec68889a614affddda5e021bd513bcf4fb2fae4a3bbe08cf0de84f037cd58478a89665dfce1ded2595c7@34.236.37.74:30303", "enode://f1a5100a81cb73163ae450c584d06b1f644aa4fad4486c6aeb4c384b343c54bb66c744aa5f133af66ea1b25f0f4a454f04878f3e96ee4cd2390c047396d6357b@209.97.158.4:30303", "enode://0d1e0372f63a3f0b82d66635ea101ecc0f6797788a078805cc933dd93e6a22f7c9fa51ab4e2d21da02d04480ef19f3bbb9a2b41dd1c262085d295a354bb8b0f9@18.217.47.209:30303", - "enode://ab083db73da15b3995ac9c68035cdb32901835a823cb848fccb672e43dd21f14428706118d6fe5b921d8e741f122f35aad0255bc86807b1d17bcfa1e86e40a14@165.227.37.104:30303", + "enode://875e1bd1b98019a5d6d588c23f68534b75462dd6ecbb3dd058221dbf7aa923f0ab782ab93bb82d42edc9996f7f0816a318bdc761e55c02b95e1169cef66f7edc@159.203.24.35:30303", "enode://8e0af07c86ec36590bb6368e7ad0c45b6dc658f5fb66ec68889a614affddda5e021bd513bcf4fb2fae4a3bbe08cf0de84f037cd58478a89665dfce1ded2595c7@34.236.37.74:30303", "enode://182ee200ca134dc4d6390f3d5aadbcd80df0f7f24335830335d142573eacce4eeb919d30e82c5df588034e167e6ba6dd11187502ac9264a71005127f6b146a99@159.203.95.241:30303", "enode://b022ff70b5fcaf9596ae5efed99a8198b4ae0578ee9d17b733609d803a75cef95d3a2a18e50dca9a7c3b26139f158c59eaf8b5fb8d1d331c9a46934a78acabe8@206.189.76.128:30303" diff --git a/ethcore/res/ethereum/xdai.json b/ethcore/res/ethereum/xdai.json new file mode 100644 index 00000000000..ad2aa395eea --- /dev/null +++ b/ethcore/res/ethereum/xdai.json @@ -0,0 +1,152 @@ +{ + "name": "xDai Chain", + "dataDir": "xdai", + "engine": { + "authorityRound": { + "params": { + "stepDuration": 5, + "blockReward": "0x0", + "maximumUncleCountTransition": 0, + "maximumUncleCount": 0, + "validators": { + "multi": { + "0": { + "list": ["0xcace5b3c29211740e595850e80478416ee77ca21"] + }, + "1300": { + "safeContract": "0x22e1229a2c5b95a60983b5577f745a603284f535" + } + } + }, + "blockRewardContractAddress": "0x867305d19606aadba405ce534e303d0e225f9556", + "blockRewardContractTransition": 1310 + } + } + }, + "params": { + "gasLimitBoundDivisor": "0x400", + "maximumExtraDataSize": "0x20", + "minGasLimit": "0x1388", + "networkID": "100", + "eip140Transition": "0x0", + "eip211Transition": "0x0", + "eip214Transition": "0x0", + "eip658Transition": "0x0", + "eip145Transition": 1604400, + "eip1014Transition": 1604400, + "eip1052Transition": 1604400, + "eip1283Transition": 1604400, + "eip1283DisableTransition": 2508800, + "registrar": "0x1ec97dc137f5168af053c24460a1200502e1a9d2" + }, + "genesis": { + "seal": { + "authorityRound": { + "step": "0x0", + "signature": "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + } + }, + "difficulty": "0x20000", + "gasLimit": "0x989680" + }, + "accounts": { + "0000000000000000000000000000000000000005": { + "builtin": { + "name": "modexp", + "activate_at": "0x0", + "pricing": { + "modexp": { + "divisor": 20 + } + } + } + }, + "0000000000000000000000000000000000000006": { + "builtin": { + "name": "alt_bn128_add", + "activate_at": "0x0", + "pricing": { + "linear": { + "base": 500, + "word": 0 + } + } + } + }, + "0000000000000000000000000000000000000007": { + "builtin": { + "name": "alt_bn128_mul", + "activate_at": "0x0", + "pricing": { + "linear": { + "base": 40000, + "word": 0 + } + } + } + }, + "0000000000000000000000000000000000000008": { + "builtin": { + "name": "alt_bn128_pairing", + "activate_at": "0x0", + "pricing": { + "alt_bn128_pairing": { + "base": 100000, + "pair": 80000 + } + } + } + }, + "0x0000000000000000000000000000000000000001": { + "balance": "1", + "builtin": { + "name": "ecrecover", + "pricing": { + "linear": { + "base": 3000, + "word": 0 + } + } + } + }, + "0x0000000000000000000000000000000000000002": { + "balance": "1", + "builtin": { + "name": "sha256", + "pricing": { + "linear": { + "base": 60, + "word": 12 + } + } + } + }, + "0x0000000000000000000000000000000000000003": { + "balance": "1", + "builtin": { + "name": "ripemd160", + "pricing": { + "linear": { + "base": 600, + "word": 120 + } + } + } + }, + "0x0000000000000000000000000000000000000004": { + "balance": "1", + "builtin": { + "name": "identity", + "pricing": { + "linear": { + "base": 15, + "word": 3 + } + } + } + } + }, + "nodes": [ + "enode://66786c15390cb4fef3743571e12ec54ca343e7f119018136d68b670edd93604eedf74e5013dc5c2439f89e0e05593e29c409a97e155ea4165c6b832de131ef1e@3.214.113.185:30303" + ] +} diff --git a/ethcore/spec/src/chain.rs b/ethcore/spec/src/chain.rs index db4e2054040..4fd9b4d307e 100644 --- a/ethcore/spec/src/chain.rs +++ b/ethcore/spec/src/chain.rs @@ -71,6 +71,7 @@ bundle_release_spec! { "ethereum/morden" => new_morden, "ethereum/musicoin" => new_musicoin, "ethereum/poacore" => new_poanet, + "ethereum/xdai" => new_xdai, "ethereum/poasokol" => new_sokol, "ethereum/rinkeby" => new_rinkeby, "ethereum/ropsten" => new_ropsten, diff --git a/parity/cli/mod.rs b/parity/cli/mod.rs index a38f2b944d5..efa1429cf65 100644 --- a/parity/cli/mod.rs +++ b/parity/cli/mod.rs @@ -300,7 +300,7 @@ usage! { ARG arg_chain: (String) = "foundation", or |c: &Config| c.parity.as_ref()?.chain.clone(), "--chain=[CHAIN]", - "Specify the blockchain type. CHAIN may be either a JSON chain specification file or ethereum, classic, poacore, volta, ewc, musicoin, ellaism, mix, callisto, morden, ropsten, kovan, rinkeby, goerli, kotti, poasokol, testnet, or dev.", + "Specify the blockchain type. CHAIN may be either a JSON chain specification file or ethereum, classic, poacore, xdai, volta, ewc, musicoin, ellaism, mix, callisto, morden, ropsten, kovan, rinkeby, goerli, kotti, poasokol, testnet, or dev.", ARG arg_keys_path: (String) = "$BASE/keys", or |c: &Config| c.parity.as_ref()?.keys_path.clone(), "--keys-path=[PATH]", diff --git a/parity/params.rs b/parity/params.rs index f82aa0749dd..fafc94d806b 100644 --- a/parity/params.rs +++ b/parity/params.rs @@ -34,6 +34,7 @@ pub enum SpecType { Foundation, Classic, Poanet, + Xdai, Volta, Ewc, Musicoin, @@ -65,6 +66,7 @@ impl str::FromStr for SpecType { "ethereum" | "frontier" | "homestead" | "byzantium" | "foundation" | "mainnet" => SpecType::Foundation, "classic" | "frontier-dogmatic" | "homestead-dogmatic" => SpecType::Classic, "poanet" | "poacore" => SpecType::Poanet, + "xdai" => SpecType::Xdai, "volta" => SpecType::Volta, "ewc" | "energyweb" => SpecType::Ewc, "musicoin" => SpecType::Musicoin, @@ -91,6 +93,7 @@ impl fmt::Display for SpecType { SpecType::Foundation => "foundation", SpecType::Classic => "classic", SpecType::Poanet => "poanet", + SpecType::Xdai => "xdai", SpecType::Volta => "volta", SpecType::Ewc => "energyweb", SpecType::Musicoin => "musicoin", @@ -117,6 +120,7 @@ impl SpecType { SpecType::Foundation => Ok(spec::new_foundation(params)), SpecType::Classic => Ok(spec::new_classic(params)), SpecType::Poanet => Ok(spec::new_poanet(params)), + SpecType::Xdai => Ok(spec::new_xdai(params)), SpecType::Volta => Ok(spec::new_volta(params)), SpecType::Ewc => Ok(spec::new_ewc(params)), SpecType::Musicoin => Ok(spec::new_musicoin(params)), @@ -371,6 +375,7 @@ mod tests { assert_eq!(SpecType::Classic, "homestead-dogmatic".parse().unwrap()); assert_eq!(SpecType::Poanet, "poanet".parse().unwrap()); assert_eq!(SpecType::Poanet, "poacore".parse().unwrap()); + assert_eq!(SpecType::Xdai, "xdai".parse().unwrap()); assert_eq!(SpecType::Volta, "volta".parse().unwrap()); assert_eq!(SpecType::Ewc, "ewc".parse().unwrap()); assert_eq!(SpecType::Ewc, "energyweb".parse().unwrap()); @@ -401,6 +406,7 @@ mod tests { assert_eq!(format!("{}", SpecType::Foundation), "foundation"); assert_eq!(format!("{}", SpecType::Classic), "classic"); assert_eq!(format!("{}", SpecType::Poanet), "poanet"); + assert_eq!(format!("{}", SpecType::Xdai), "xdai"); assert_eq!(format!("{}", SpecType::Volta), "volta"); assert_eq!(format!("{}", SpecType::Ewc), "energyweb"); assert_eq!(format!("{}", SpecType::Musicoin), "musicoin"); From dabfa2c6634cc70845f6875b86db48a1af74c98c Mon Sep 17 00:00:00 2001 From: David Date: Thu, 29 Aug 2019 13:19:55 +0200 Subject: [PATCH 7/7] EIP 1884 Re-pricing of trie-size dependent operations (#10992) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add client-traits crate Move the BlockInfo trait to new crate * New crate `machine` Contains code extracted from ethcore that defines `Machine`, `Externalities` and other execution related code. * Use new machine and client-traits crates in ethcore * Use new crates machine and client-traits instead of ethcore where appropriate * Fix tests * Don't re-export so many types from ethcore::client * Fixing more fallout from removing re-export * fix test * More fallout from not re-exporting types * Add some docs * cleanup * import the macro edition style * Tweak docs * Add missing import * remove unused ethabi_derive imports * Use latest ethabi-contract * Move many traits from ethcore/client/traits to client-traits crate Initial version of extracted Engine trait * Move snapshot related traits to the engine crate (eew) * Move a few snapshot related types to common_types Cleanup Executed as exported from machine crate * fix warning * Gradually introduce new engine crate: snapshot * ethcore typechecks with new engine crate * Sort out types outside ethcore * Add an EpochVerifier to ethash and use that in Engine.epoch_verifier() Cleanup * Document pub members * Sort out tests Sort out default impls for EpochVerifier * Add test-helpers feature and move EngineSigner impl to the right place * Sort out tests * Sort out tests and refactor verification types * Fix missing traits * More missing traits Fix Histogram * Fix tests and cleanup * cleanup * Put back needed logger import * Don't rexport common_types from ethcore/src/client Don't export ethcore::client::* * Remove files no longer used Use types from the engine crate Explicit exports from engine::engine * Get rid of itertools * Move a few more traits from ethcore to client-traits: BlockChainReset, ScheduleInfo, StateClient * Move ProvingBlockChainClient to client-traits * Don't re-export ForkChoice and Transition from ethcore * Address grumbles: sort imports, remove commented out code * Fix merge resolution error * Extract the Clique engine to own crate * Extract NullEngine and the block_reward module from ethcore * Extract InstantSeal engine to own crate * Extract remaining engines * Extract executive_state to own crate so it can be used by engine crates * Remove snapshot stuff from the engine crate * Put snapshot traits back in ethcore * cleanup * Remove stuff from ethcore * Don't use itertools * itertools in aura is legit-ish * More post-merge fixes * Re-export less types in client * cleanup * Extract spec to own crate * Put back the test-helpers from basic-authority * Fix ethcore benchmarks * Reduce the public api of ethcore/verification * WIP * Add Cargo.toml * Fix compilation outside ethcore * Audit uses of import_verified_blocks() and remove unneeded calls Cleanup * cleanup * Remove unused imports from ethcore * Cleanup * remove double semi-colons * Add missing generic param * More missing generics * Update ethcore/block-reward/Cargo.toml Co-Authored-By: Tomasz Drwięga * Update ethcore/engines/basic-authority/Cargo.toml Co-Authored-By: Tomasz Drwięga * Update ethcore/engines/ethash/Cargo.toml Co-Authored-By: Tomasz Drwięga * Update ethcore/engines/clique/src/lib.rs Co-Authored-By: Tomasz Drwięga * signers is already a ref * Add an EngineType enum to tighten up Engine.name() * Add CHAINID opcode * Introduce Snapshotting enum to distinguish the type of snapshots a chain uses * Rename supports_warp to snapshot_mode * Missing import * Add chain_id wherever we instantiate EnvInfo * more missing chain_id * Tell serde to ignore the chain_id field on Env * Update ethcore/src/snapshot/consensus/mod.rs Co-Authored-By: Tomasz Drwięga * Use the chain_id from the machine by adding chain_id() to the Ext trait * cleanup * add missing impl cleanup * missing import * Fix import * Add transition marker for EIP 1344 * double semi * Fix merge problem * cleanup * reprice SLOAD to 800 gas * Reprice BALANCE and EXTCODEHASH * Add SELFBALANCE opcode * Add test for SELFBALANCE Use InstructionParams.address as the self-address * Use easier to read values in test * merge conflict error * Fix a few warnings * Update ethcore/vm/src/schedule.rs Co-Authored-By: Andronik Ordian * more merge fallout --- ethcore/evm/src/evm.rs | 18 ++++++++++++------ ethcore/evm/src/instructions.rs | 3 +++ ethcore/evm/src/interpreter/mod.rs | 15 ++++++++++++--- ethcore/evm/src/tests.rs | 26 ++++++++++++++++++++++++++ ethcore/types/src/engines/params.rs | 13 +++++++++++++ ethcore/vm/src/ext.rs | 2 +- ethcore/vm/src/return_data.rs | 6 +----- ethcore/vm/src/schedule.rs | 17 ++++++++++++++--- json/src/spec/params.rs | 2 ++ 9 files changed, 84 insertions(+), 18 deletions(-) diff --git a/ethcore/evm/src/evm.rs b/ethcore/evm/src/evm.rs index f8a08b2b2e3..3c88155f2f5 100644 --- a/ethcore/evm/src/evm.rs +++ b/ethcore/evm/src/evm.rs @@ -44,12 +44,18 @@ pub trait Finalize { impl Finalize for Result { fn finalize(self, ext: E) -> Result { match self { - Ok(GasLeft::Known(gas_left)) => Ok(FinalizationResult { gas_left: gas_left, apply_state: true, return_data: ReturnData::empty() }), - Ok(GasLeft::NeedsReturn { gas_left, data, apply_state }) => ext.ret(&gas_left, &data, apply_state).map(|gas_left| FinalizationResult { - gas_left: gas_left, - apply_state: apply_state, - return_data: data, - }), + Ok(GasLeft::Known(gas_left)) => { + Ok(FinalizationResult { + gas_left, + apply_state: true, + return_data: ReturnData::empty() + }) + }, + Ok(GasLeft::NeedsReturn { gas_left, data, apply_state }) => { + ext.ret(&gas_left, &data, apply_state).map(|gas_left| + FinalizationResult { gas_left, apply_state, return_data: data } + ) + }, Err(err) => Err(err), } } diff --git a/ethcore/evm/src/instructions.rs b/ethcore/evm/src/instructions.rs index 1580f7b591d..b0a66c159e3 100644 --- a/ethcore/evm/src/instructions.rs +++ b/ethcore/evm/src/instructions.rs @@ -151,6 +151,8 @@ enum_with_from_u8! { GASLIMIT = 0x45, #[doc = "get chain ID"] CHAINID = 0x46, + #[doc = "get balance of own account"] + SELFBALANCE = 0x47, #[doc = "remove item from stack"] POP = 0x50, @@ -502,6 +504,7 @@ lazy_static! { arr[DIFFICULTY as usize] = Some(InstructionInfo::new("DIFFICULTY", 0, 1, GasPriceTier::Base)); arr[GASLIMIT as usize] = Some(InstructionInfo::new("GASLIMIT", 0, 1, GasPriceTier::Base)); arr[CHAINID as usize] = Some(InstructionInfo::new("CHAINID", 0, 1, GasPriceTier::Base)); + arr[SELFBALANCE as usize] = Some(InstructionInfo::new("SELFBALANCE", 0, 1, GasPriceTier::Low)); arr[POP as usize] = Some(InstructionInfo::new("POP", 1, 0, GasPriceTier::Base)); arr[MLOAD as usize] = Some(InstructionInfo::new("MLOAD", 1, 1, GasPriceTier::VeryLow)); arr[MSTORE as usize] = Some(InstructionInfo::new("MSTORE", 2, 0, GasPriceTier::VeryLow)); diff --git a/ethcore/evm/src/interpreter/mod.rs b/ethcore/evm/src/interpreter/mod.rs index 85564385552..47260139521 100644 --- a/ethcore/evm/src/interpreter/mod.rs +++ b/ethcore/evm/src/interpreter/mod.rs @@ -299,7 +299,12 @@ impl Interpreter { let result = if self.gasometer.is_none() { InterpreterResult::Done(Err(vm::Error::OutOfGas)) } else if self.reader.len() == 0 { - InterpreterResult::Done(Ok(GasLeft::Known(self.gasometer.as_ref().expect("Gasometer None case is checked above; qed").current_gas.as_u256()))) + let current_gas = self.gasometer + .as_ref() + .expect("Gasometer None case is checked above; qed") + .current_gas + .as_u256(); + InterpreterResult::Done(Ok(GasLeft::Known(current_gas))) } else { self.step_inner(ext) }; @@ -308,7 +313,7 @@ impl Interpreter { self.done = true; self.informant.done(); } - return result; + result } /// Inner helper function for step. @@ -429,7 +434,8 @@ impl Interpreter { (instruction == instructions::REVERT && !schedule.have_revert) || ((instruction == instructions::SHL || instruction == instructions::SHR || instruction == instructions::SAR) && !schedule.have_bitwise_shifting) || (instruction == instructions::EXTCODEHASH && !schedule.have_extcodehash) || - (instruction == instructions::CHAINID && !schedule.have_chain_id) + (instruction == instructions::CHAINID && !schedule.have_chain_id) || + (instruction == instructions::SELFBALANCE && !schedule.have_selfbalance) { return Err(vm::Error::BadInstruction { instruction: instruction as u8 @@ -847,6 +853,9 @@ impl Interpreter { instructions::CHAINID => { self.stack.push(ext.chain_id().into()) }, + instructions::SELFBALANCE => { + self.stack.push(ext.balance(&self.params.address)?); + } // Stack instructions diff --git a/ethcore/evm/src/tests.rs b/ethcore/evm/src/tests.rs index 05a39e1b5a1..d226b7c1a25 100644 --- a/ethcore/evm/src/tests.rs +++ b/ethcore/evm/src/tests.rs @@ -124,6 +124,32 @@ fn test_origin(factory: super::Factory) { assert_store(&ext, 0, "000000000000000000000000cd1722f2947def4cf144679da39c4c32bdc35681"); } +evm_test!{test_selfbalance: test_selfbalance_int} +fn test_selfbalance(factory: super::Factory) { + let own_addr = Address::from_str("1337000000000000000000000000000000000000").unwrap(); + // 47 SELFBALANCE + // 60 ff PUSH ff + // 55 SSTORE + let code = hex!("47 60 ff 55").to_vec(); + + let mut params = ActionParams::default(); + params.address = own_addr.clone(); + params.gas = U256::from(100_000); + params.code = Some(Arc::new(code)); + let mut ext = FakeExt::new_istanbul(); + ext.balances = { + let mut x = HashMap::new(); + x.insert(own_addr, U256::from(1_025)); // 0x401 + x + }; + let gas_left = { + let vm = factory.create(params, ext.schedule(), ext.depth()); + test_finalize(vm.exec(&mut ext).ok().unwrap()).unwrap() + }; + assert_eq!(gas_left, U256::from(79_992)); // TODO[dvdplm]: do the sums here, SELFBALANCE-5 + PUSH1-3 + ONEBYTE-4 + SSTORE-?? = 100_000 - 79_992 + assert_store(&ext, 0xff, "0000000000000000000000000000000000000000000000000000000000000401"); +} + evm_test!{test_sender: test_sender_int} fn test_sender(factory: super::Factory) { let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap(); diff --git a/ethcore/types/src/engines/params.rs b/ethcore/types/src/engines/params.rs index fc8eb96674c..7176093f34b 100644 --- a/ethcore/types/src/engines/params.rs +++ b/ethcore/types/src/engines/params.rs @@ -92,6 +92,8 @@ pub struct CommonParams { pub eip1014_transition: BlockNumber, /// Number of first block where EIP-1344 rules begin: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1344.md pub eip1344_transition: BlockNumber, + /// Number of first block where EIP-1884 rules begin:https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1884.md + pub eip1884_transition: BlockNumber, /// Number of first block where EIP-2028 rules begin. pub eip2028_transition: BlockNumber, /// Number of first block where dust cleanup rules (EIP-168 and EIP169) begin. @@ -165,6 +167,13 @@ impl CommonParams { schedule.have_extcodehash = block_number >= self.eip1052_transition; schedule.have_chain_id = block_number >= self.eip1344_transition; schedule.eip1283 = block_number >= self.eip1283_transition && !(block_number >= self.eip1283_disable_transition); + + if block_number >= self.eip1884_transition { + schedule.have_selfbalance = true; + schedule.sload_gas = 800; + schedule.balance_gas = 700; + schedule.extcodehash_gas = 700; + } if block_number >= self.eip2028_transition { schedule.tx_data_non_zero_gas = 16; } @@ -289,6 +298,10 @@ impl From for CommonParams { BlockNumber::max_value, Into::into, ), + eip1884_transition: p.eip1884_transition.map_or_else( + BlockNumber::max_value, + Into::into, + ), eip2028_transition: p.eip2028_transition.map_or_else( BlockNumber::max_value, Into::into, diff --git a/ethcore/vm/src/ext.rs b/ethcore/vm/src/ext.rs index 63d9595fb0a..68e5822e451 100644 --- a/ethcore/vm/src/ext.rs +++ b/ethcore/vm/src/ext.rs @@ -91,7 +91,7 @@ pub trait Ext { /// Creates new contract. /// - /// Returns gas_left and contract address if contract creation was succesfull. + /// Returns gas_left and contract address if contract creation was successful. fn create( &mut self, gas: &U256, diff --git a/ethcore/vm/src/return_data.rs b/ethcore/vm/src/return_data.rs index 85fdb361db5..38ac23ffdc8 100644 --- a/ethcore/vm/src/return_data.rs +++ b/ethcore/vm/src/return_data.rs @@ -44,11 +44,7 @@ impl ReturnData { } /// Create `ReturnData` from give buffer and slice. pub fn new(mem: Vec, offset: usize, size: usize) -> Self { - ReturnData { - mem: mem, - offset: offset, - size: size, - } + ReturnData { mem, offset, size } } } diff --git a/ethcore/vm/src/schedule.rs b/ethcore/vm/src/schedule.rs index e11603ecdaa..877ef145b65 100644 --- a/ethcore/vm/src/schedule.rs +++ b/ethcore/vm/src/schedule.rs @@ -19,11 +19,13 @@ use std::collections::HashMap; use ethereum_types::U256; /// Definition of schedules that can be applied to a version. +#[derive(Debug)] pub enum VersionedSchedule { PWasm, } /// Definition of the cost schedule and other parameterisations for the EVM. +#[derive(Debug)] pub struct Schedule { /// Does it support exceptional failed code deposit pub exceptional_failed_code_deposit: bool, @@ -124,6 +126,8 @@ pub struct Schedule { pub have_bitwise_shifting: bool, /// CHAINID opcode enabled. pub have_chain_id: bool, + /// SELFBALANCE opcode enabled. + pub have_selfbalance: bool, /// Kill basic accounts below this balance if touched. pub kill_dust: CleanDustMode, /// Enable EIP-1283 rules @@ -139,6 +143,7 @@ pub struct Schedule { } /// Wasm cost table +#[derive(Debug)] pub struct WasmCosts { /// Default opcode cost pub regular: u32, @@ -192,7 +197,7 @@ impl Default for WasmCosts { } /// Dust accounts cleanup mode. -#[derive(PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq)] pub enum CleanDustMode { /// Dust cleanup is disabled. Off, @@ -223,6 +228,7 @@ impl Schedule { have_return_data: false, have_bitwise_shifting: false, have_chain_id: false, + have_selfbalance: false, have_extcodehash: false, stack_limit: 1024, max_depth: 1024, @@ -294,8 +300,12 @@ impl Schedule { /// Schedule for the Istanbul fork of the Ethereum main net. pub fn new_istanbul() -> Schedule { let mut schedule = Self::new_constantinople(); - schedule.have_chain_id = true; - schedule.tx_data_non_zero_gas = 16; + schedule.have_chain_id = true; // EIP 1344 + schedule.tx_data_non_zero_gas = 16; // EIP 2028 + schedule.sload_gas = 800; // EIP 1884 + schedule.balance_gas = 700; // EIP 1884 + schedule.extcodehash_gas = 700; // EIP 1884 + schedule.have_selfbalance = true; // EIP 1884 schedule } @@ -308,6 +318,7 @@ impl Schedule { have_return_data: false, have_bitwise_shifting: false, have_chain_id: false, + have_selfbalance: false, have_extcodehash: false, stack_limit: 1024, max_depth: 1024, diff --git a/json/src/spec/params.rs b/json/src/spec/params.rs index 29c842b87bb..7b1cd1c188c 100644 --- a/json/src/spec/params.rs +++ b/json/src/spec/params.rs @@ -96,6 +96,8 @@ pub struct Params { /// See `CommonParams` docs. pub eip1344_transition: Option, /// See `CommonParams` docs. + pub eip1884_transition: Option, + /// See `CommonParams` docs. pub eip2028_transition: Option, /// See `CommonParams` docs. pub dust_protection_transition: Option,