Skip to content
service.rs 1.88 KiB
Newer Older
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
use util::*;
use sync::*;
use spec::Spec;
use error::*;
use std::env;
use client::Client;

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 {
	net_service: NetworkService<SyncMessage>,
	client: Arc<RwLock<Client>>,
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(spec: Spec) -> Result<ClientService, Error> {
		let mut net_service = try!(NetworkService::start());
		info!("Starting {}", net_service.host_info());
		info!("Configured for {} using {} engine", spec.name, spec.engine_name);
		let mut dir = env::home_dir().unwrap();
		dir.push(".parity");
		dir.push(H64::from(spec.genesis_header().hash()).hex());
		let client = Arc::new(RwLock::new(try!(Client::new(spec, &dir, net_service.io().channel()))));
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
		EthSync::register(&mut net_service, client.clone());
		let client_io = Box::new(ClientIoHandler {
			client: client.clone()
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
		});
		try!(net_service.io().register_handler(client_io));

		Ok(ClientService {
			net_service: net_service,
			client: client,
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
		})
	}

	pub fn io(&mut self) -> &mut IoService<NetSyncMessage> {
		self.net_service.io()
	}

	pub fn client(&self) -> Arc<RwLock<Client>> {
		self.client.clone()
	}
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
}

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
/// IO interface for the Client handler
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
struct ClientIoHandler {
	client: Arc<RwLock<Client>>
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
}

impl IoHandler<NetSyncMessage> for ClientIoHandler {
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	fn initialize<'s>(&'s mut self, _io: &mut IoContext<'s, NetSyncMessage>) { }
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed

	fn message<'s>(&'s mut self, _io: &mut IoContext<'s, NetSyncMessage>, net_message: &'s mut NetSyncMessage) {
		match net_message {
			&mut UserMessage(ref mut message) =>  {
				match message {
					&mut SyncMessage::BlockVerified(ref mut bytes) => {
						self.client.write().unwrap().import_verified_block(mem::replace(bytes, Bytes::new()));
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
					},
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
					_ => {}, // ignore other messages
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
			_ => {}, // ignore other messages