openethereum/ethcore/service/src/service.rs

277 lines
9.3 KiB
Rust
Raw Normal View History

2020-09-22 14:53:52 +02:00
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
// This file is part of OpenEthereum.
2016-02-05 13:40:41 +01:00
2020-09-22 14:53:52 +02:00
// OpenEthereum is free software: you can redistribute it and/or modify
2016-02-05 13:40:41 +01:00
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
2020-09-22 14:53:52 +02:00
// OpenEthereum is distributed in the hope that it will be useful,
2016-02-05 13:40:41 +01:00
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
2020-09-22 14:53:52 +02:00
// along with OpenEthereum. If not, see <http://www.gnu.org/licenses/>.
2016-02-05 13:40:41 +01:00
2016-02-02 15:29:53 +01:00
//! Creates and registers client and network services.
2020-08-05 06:08:03 +02:00
use std::{path::Path, sync::Arc, time::Duration};
use ansi_term::Colour;
2020-08-05 06:08:03 +02:00
use io::{IoContext, IoError, IoHandler, IoService, TimerToken};
use stop_guard::StopGuard;
use blockchain::{BlockChainDB, BlockChainDBHandler};
2020-08-05 06:08:03 +02:00
use ethcore::{
client::{ChainNotify, Client, ClientConfig, ClientIoMessage},
error::{Error as EthcoreError, ErrorKind},
miner::Miner,
snapshot::{
service::{Service as SnapshotService, ServiceParams as SnapServiceParams},
Error as SnapshotError, RestorationStatus, SnapshotService as _SnapshotService,
},
spec::Spec,
};
Private transactions integration pr (#6422) * Private transaction message added * Empty line removed * Private transactions logic removed from client into the separate module * Fixed compilation after merge with head * Signed private transaction message added as well * Comments after the review fixed * Private tx execution * Test update * Renamed some methods * Fixed some tests * Reverted submodules * Fixed build * Private transaction message added * Empty line removed * Private transactions logic removed from client into the separate module * Fixed compilation after merge with head * Signed private transaction message added as well * Comments after the review fixed * Encrypted private transaction message and signed reply added * Private tx execution * Test update * Main scenario completed * Merged with the latest head * Private transactions API * Comments after review fixed * Parameters for private transactions added to parity arguments * New files added * New API methods added * Do not process packets from unconfirmed peers * Merge with ptm_ss branch * Encryption and permissioning with key server added * Fixed compilation after merge * Version of Parity protocol incremented in order to support private transactions * Doc strings for constants added * Proper format for doc string added * fixed some encryptor.rs grumbles * Private transactions functionality moved to the separate crate * Refactoring in order to remove late initialisation * Tests fixed after moving to the separate crate * Fetch method removed * Sync test helpers refactored * Interaction with encryptor refactored * Contract address retrieving via substate removed * Sensible gas limit for private transactions implemented * New private contract with nonces added * Parsing of the response from key server fixed * Build fixed after the merge, native contracts removed * Crate renamed * Tests moved to the separate directory * Handling of errors reworked in order to use error chain * Encodable macro added, new constructor replaced with default * Native ethabi usage removed * Couple conversions optimized * Interactions with client reworked * Errors omitting removed * Fix after merge * Fix after the merge * private transactions improvements in progress * private_transactions -> ethcore/private-tx * making private transactions more idiomatic * private-tx encryptor uses shared FetchClient and is more idiomatic * removed redundant tests, moved integration tests to tests/ dir * fixed failing service test * reenable add_notify on private tx provider * removed private_tx tests from sync module * removed commented out code * Use plain password instead of unlocking account manager * remove dead code * Link to the contract changed * Transaction signature chain replay protection module created * Redundant type conversion removed * Contract address returned by private provider * Test fixed * Addressing grumbles in PrivateTransactions (#8249) * Tiny fixes part 1. * A bunch of additional comments and todos. * Fix ethsync tests. * resolved merge conflicts * final private tx pr (#8318) * added cli option that enables private transactions * fixed failing test * fixed failing test * fixed failing test * fixed failing test
2018-04-09 16:14:33 +02:00
use Error;
2016-01-15 01:03:29 +01:00
/// Client service setup. Creates and registers client and network services with the IO subsystem.
2016-01-13 23:15:53 +01:00
pub struct ClientService {
2020-08-05 06:08:03 +02:00
io_service: Arc<IoService<ClientIoMessage>>,
client: Arc<Client>,
snapshot: Arc<SnapshotService>,
2020-07-29 10:36:15 +02:00
database: Arc<dyn BlockChainDB>,
2020-08-05 06:08:03 +02:00
_stop_guard: StopGuard,
2016-01-13 23:15:53 +01:00
}
impl ClientService {
2020-08-05 06:08:03 +02:00
/// Start the `ClientService`.
pub fn start(
config: ClientConfig,
spec: &Spec,
2020-07-29 10:36:15 +02:00
blockchain_db: Arc<dyn BlockChainDB>,
2020-08-05 06:08:03 +02:00
snapshot_path: &Path,
2020-07-29 10:36:15 +02:00
restoration_db_handler: Box<dyn BlockChainDBHandler>,
2020-08-05 06:08:03 +02:00
_ipc_path: &Path,
miner: Arc<Miner>,
) -> Result<ClientService, Error> {
let io_service = IoService::<ClientIoMessage>::start()?;
info!(
"Configured for {} using {} engine",
Colour::White.bold().paint(spec.name.clone()),
Colour::Yellow.bold().paint(spec.engine.name())
);
let pruning = config.pruning;
let client = Client::new(
config,
&spec,
blockchain_db.clone(),
miner.clone(),
io_service.channel(),
)?;
miner.set_io_channel(io_service.channel());
miner.set_in_chain_checker(&client.clone());
let snapshot_params = SnapServiceParams {
engine: spec.engine.clone(),
genesis_block: spec.genesis_block(),
restoration_db_handler: restoration_db_handler,
pruning: pruning,
channel: io_service.channel(),
snapshot_root: snapshot_path.into(),
client: client.clone(),
};
let snapshot = Arc::new(SnapshotService::new(snapshot_params)?);
let client_io = Arc::new(ClientIoHandler {
client: client.clone(),
snapshot: snapshot.clone(),
});
io_service.register_handler(client_io)?;
spec.engine.register_client(Arc::downgrade(&client) as _);
let stop_guard = StopGuard::new();
Ok(ClientService {
io_service: Arc::new(io_service),
client: client,
snapshot: snapshot,
database: blockchain_db,
_stop_guard: stop_guard,
})
}
/// Get general IO interface
pub fn register_io_handler(
&self,
2020-07-29 10:36:15 +02:00
handler: Arc<dyn IoHandler<ClientIoMessage> + Send>,
2020-08-05 06:08:03 +02:00
) -> Result<(), IoError> {
self.io_service.register_handler(handler)
}
/// Get client interface
pub fn client(&self) -> Arc<Client> {
self.client.clone()
}
/// Get snapshot interface.
pub fn snapshot_service(&self) -> Arc<SnapshotService> {
self.snapshot.clone()
}
/// Get network service component
pub fn io(&self) -> Arc<IoService<ClientIoMessage>> {
self.io_service.clone()
}
/// Set the actor to be notified on certain chain events
2020-07-29 10:36:15 +02:00
pub fn add_notify(&self, notify: Arc<dyn ChainNotify>) {
2020-08-05 06:08:03 +02:00
self.client.add_notify(notify);
}
/// Get a handle to the database.
2020-07-29 10:36:15 +02:00
pub fn db(&self) -> Arc<dyn BlockChainDB> {
2020-08-05 06:08:03 +02:00
self.database.clone()
}
/// Shutdown the Client Service
pub fn shutdown(&self) {
trace!(target: "shutdown", "Shutting down Client Service");
self.snapshot.shutdown();
}
2016-01-13 23:15:53 +01:00
}
2016-01-15 01:03:29 +01:00
/// IO interface for the Client handler
2016-01-13 23:15:53 +01:00
struct ClientIoHandler {
2020-08-05 06:08:03 +02:00
client: Arc<Client>,
snapshot: Arc<SnapshotService>,
2016-01-13 23:15:53 +01:00
}
const CLIENT_TICK_TIMER: TimerToken = 0;
2016-09-06 17:44:11 +02:00
const SNAPSHOT_TICK_TIMER: TimerToken = 1;
const CLIENT_TICK: Duration = Duration::from_secs(5);
const SNAPSHOT_TICK: Duration = Duration::from_secs(10);
impl IoHandler<ClientIoMessage> for ClientIoHandler {
2020-08-05 06:08:03 +02:00
fn initialize(&self, io: &IoContext<ClientIoMessage>) {
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<ClientIoMessage>, timer: TimerToken) {
trace_time!("service::read");
match timer {
CLIENT_TICK_TIMER => {
use ethcore::snapshot::SnapshotService;
let snapshot_restoration =
if let RestorationStatus::Ongoing { .. } = self.snapshot.restoration_status() {
2020-08-05 06:08:03 +02:00
true
} else {
false
};
self.client.tick(snapshot_restoration)
}
SNAPSHOT_TICK_TIMER => self.snapshot.tick(),
_ => warn!("IO service triggered unregistered timer '{}'", timer),
}
}
fn message(&self, _io: &IoContext<ClientIoMessage>, net_message: &ClientIoMessage) {
trace_time!("service::message");
use std::thread;
match *net_message {
ClientIoMessage::BlockVerified => {
self.client.import_verified_blocks();
}
ClientIoMessage::BeginRestoration(ref manifest) => {
if let Err(e) = self.snapshot.init_restore(manifest.clone(), true) {
warn!("Failed to initialize snapshot restoration: {}", e);
}
}
ClientIoMessage::FeedStateChunk(ref hash, ref chunk) => {
self.snapshot.feed_state_chunk(*hash, chunk)
}
ClientIoMessage::FeedBlockChunk(ref hash, ref chunk) => {
self.snapshot.feed_block_chunk(*hash, chunk)
}
ClientIoMessage::TakeSnapshot(num) => {
let client = self.client.clone();
let snapshot = self.snapshot.clone();
let res = thread::Builder::new()
.name("Periodic Snapshot".into())
.spawn(move || {
if let Err(e) = snapshot.take_snapshot(&*client, num) {
match e {
EthcoreError(
ErrorKind::Snapshot(SnapshotError::SnapshotAborted),
_,
) => info!("Snapshot aborted"),
_ => warn!("Failed to take snapshot at block #{}: {}", num, e),
}
}
});
if let Err(e) = res {
debug!(target: "snapshot", "Failed to initialize periodic snapshot thread: {:?}", e);
}
}
ClientIoMessage::Execute(ref exec) => {
(*exec.0)(&self.client);
}
_ => {} // ignore other messages
}
}
2016-01-13 23:15:53 +01:00
}
2016-01-30 14:00:36 +01:00
#[cfg(test)]
mod tests {
2020-08-05 06:08:03 +02:00
use std::{sync::Arc, thread, time};
use tempdir::TempDir;
use super::*;
use ethcore::{client::ClientConfig, miner::Miner, spec::Spec, test_helpers};
use ethcore_db::NUM_COLUMNS;
use kvdb_rocksdb::{CompactionProfile, DatabaseConfig};
#[test]
fn it_can_be_started() {
let tempdir = TempDir::new("").unwrap();
let client_path = tempdir.path().join("client");
let snapshot_path = tempdir.path().join("snapshot");
let client_config = ClientConfig::default();
let mut client_db_config = DatabaseConfig::with_columns(NUM_COLUMNS);
client_db_config.memory_budget = client_config.db_cache_size;
client_db_config.compaction = CompactionProfile::auto(&client_path);
let client_db_handler = test_helpers::restoration_db_handler(client_db_config.clone());
let client_db = client_db_handler.open(&client_path).unwrap();
let restoration_db_handler = test_helpers::restoration_db_handler(client_db_config);
let spec = Spec::new_test();
let service = ClientService::start(
ClientConfig::default(),
&spec,
client_db,
&snapshot_path,
restoration_db_handler,
tempdir.path(),
Arc::new(Miner::new_for_tests(&spec, None)),
);
assert!(service.is_ok());
drop(service.unwrap());
thread::park_timeout(time::Duration::from_millis(100));
}
2016-02-02 15:29:53 +01:00
}