Skip to content
service.rs 4.74 KiB
Newer Older
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.

// Parity is free software: you can redistribute it and/or modify
// 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.

// Parity is distributed in the hope that it will be useful,
// 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
// along with Parity.  If not, see <http://www.gnu.org/licenses/>.

//! Creates and registers client and network services.

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
use util::*;
Tomusdrw's avatar
Tomusdrw committed
use util::panics::*;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
use spec::Spec;
use error::*;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
use client::{Client, ClientConfig};
use miner::Miner;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
/// Message type for external and internal events
#[derive(Clone)]
pub enum SyncMessage {
	/// New block has been imported into the blockchain
	NewChainBlocks {
		/// Hashes of blocks imported to blockchain
		imported: Vec<H256>,
		/// Hashes of blocks not imported to blockchain (because were invalid)
		invalid: Vec<H256>,
		/// Hashes of blocks that were removed from canonical chain
		retracted: Vec<H256>,
		/// Hashes of blocks that are now included in cannonical chain
		enacted: Vec<H256>,
	/// Best Block Hash in chain has been changed
	NewChainHead,
Tomusdrw's avatar
Tomusdrw committed
	/// A block is ready
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	BlockVerified,
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	/// Start network command.
	StartNetwork,
	/// Stop network command.
	StopNetwork,
arkpar's avatar
arkpar committed
/// IO Message type used for Network service
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
pub type NetSyncMessage = NetworkIoMessage<SyncMessage>;

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
/// Client service setup. Creates and registers client and network services with the IO subsystem.
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
pub struct ClientService {
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	net_service: Arc<NetworkService<SyncMessage>>,
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	client: Arc<Client>,
Tomusdrw's avatar
Tomusdrw committed
	panic_handler: Arc<PanicHandler>
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
}

impl ClientService {
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	/// Start the service in a separate thread.
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	pub fn start(config: ClientConfig, spec: Spec, net_config: NetworkConfiguration, db_path: &Path, miner: Arc<Miner>, enable_network: bool) -> Result<ClientService, Error> {
Tomusdrw's avatar
Tomusdrw committed
		let panic_handler = PanicHandler::new_in_arc();
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
		let net_service = try!(NetworkService::new(net_config));
Tomusdrw's avatar
Tomusdrw committed
		panic_handler.forward_from(&net_service);
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
		if enable_network {
			try!(net_service.start());
		}
		info!("Starting {}", net_service.host_info());
		info!("Configured for {} using {:?} engine", spec.name, spec.engine.name());
		let client = try!(Client::new(config, spec, db_path, miner, net_service.io().channel()));
Tomusdrw's avatar
Tomusdrw committed
		panic_handler.forward_from(client.deref());
		let client_io = Arc::new(ClientIoHandler {
			client: client.clone()
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
		});
		try!(net_service.io().register_handler(client_io));

		Ok(ClientService {
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
			net_service: Arc::new(net_service),
			client: client,
Tomusdrw's avatar
Tomusdrw committed
			panic_handler: panic_handler,
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
		})
	}
	/// Add a node to network
Gav Wood's avatar
Gav Wood committed
	pub fn add_node(&mut self, _enode: &str) {
		unimplemented!();
	}

	/// Get general IO interface
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	pub fn register_io_handler(&self, handler: Arc<IoHandler<NetSyncMessage> + Send>) -> Result<(), IoError> {
		self.net_service.io().register_handler(handler)
	/// Get client interface
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	pub fn client(&self) -> Arc<Client> {
		self.client.clone()
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	}

	/// Get network service component
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	pub fn network(&mut self) -> Arc<NetworkService<SyncMessage>> {
		self.net_service.clone()
Tomusdrw's avatar
Tomusdrw committed
impl MayPanic for ClientService {
	fn on_panic<F>(&self, closure: F) where F: OnPanicListener {
		self.panic_handler.on_panic(closure);
	}
}

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
/// IO interface for the Client handler
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
struct ClientIoHandler {
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	client: Arc<Client>
const CLIENT_TICK_TIMER: TimerToken = 0;
const CLIENT_TICK_MS: u64 = 5000;

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
impl IoHandler<NetSyncMessage> for ClientIoHandler {
	fn initialize(&self, io: &IoContext<NetSyncMessage>) {
		io.register_timer(CLIENT_TICK_TIMER, CLIENT_TICK_MS).expect("Error registering client timer");
	}

	fn timeout(&self, _io: &IoContext<NetSyncMessage>, timer: TimerToken) {
		if timer == CLIENT_TICK_TIMER {
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
			self.client.tick();
Gav Wood's avatar
Gav Wood committed
	}
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed

	#[cfg_attr(feature="dev", allow(single_match))]
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	fn message(&self, io: &IoContext<NetSyncMessage>, net_message: &NetSyncMessage) {
		if let UserMessage(ref message) = *net_message {
			match *message {
				SyncMessage::BlockVerified => {
					self.client.import_verified_blocks(&io.channel());
				},
				_ => {}, // ignore other messages
Nikolay Volf's avatar
Nikolay Volf committed
#[cfg(test)]
mod tests {
	use super::*;
	use tests::helpers::*;
	use util::network::*;
	use devtools::*;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	use client::ClientConfig;
Nikolay Volf's avatar
Nikolay Volf committed
	use std::sync::Arc;
	use miner::Miner;
Nikolay Volf's avatar
Nikolay Volf committed

Nikolay Volf's avatar
Nikolay Volf committed
	#[test]
	fn it_can_be_started() {
		let spec = get_test_spec();
Nikolay Volf's avatar
Nikolay Volf committed
		let temp_path = RandomTempPath::new();
Nikolay Volf's avatar
Nikolay Volf committed
		let service = ClientService::start(ClientConfig::default(), spec, NetworkConfiguration::new_local(), &temp_path.as_path(), Arc::new(Miner::default()));
Nikolay Volf's avatar
Nikolay Volf committed
		assert!(service.is_ok());
	}