git.delta.rocks / unique-network / refs/commits / c6880a4e70ee

difftreelog

source

node/src/service.rs10.4 KiBsourcehistory
1//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.23//4// This file is subject to the terms and conditions defined in5// file 'LICENSE', which is part of this source code package.6//78use std::sync::Arc;9use std::time::Duration;10use sc_client_api::{ExecutorProvider, RemoteBackend};11use nft_runtime::{self, opaque::Block, RuntimeApi};12use sc_service::{error::Error as ServiceError, Configuration, TaskManager};13use sp_inherents::InherentDataProviders;14use sc_executor::native_executor_instance;15pub use sc_executor::NativeExecutor;16use sp_consensus_aura::sr25519::{AuthorityPair as AuraPair};17use sc_finality_grandpa::SharedVoterState;18use sc_keystore::LocalKeystore;19use sc_telemetry::TelemetrySpan;2021// Our native executor instance.22native_executor_instance!(23	pub Executor,24	nft_runtime::api::dispatch,25	nft_runtime::native_version,26	frame_benchmarking::benchmarking::HostFunctions,27);2829type FullClient = sc_service::TFullClient<Block, RuntimeApi, Executor>;30type FullBackend = sc_service::TFullBackend<Block>;31type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;3233pub fn new_partial(config: &Configuration) -> Result<sc_service::PartialComponents<34	FullClient, FullBackend, FullSelectChain,35	sp_consensus::DefaultImportQueue<Block, FullClient>,36	sc_transaction_pool::FullPool<Block, FullClient>,37	(38		sc_consensus_aura::AuraBlockImport<39			Block,40			FullClient,41			sc_finality_grandpa::GrandpaBlockImport<FullBackend, Block, FullClient, FullSelectChain>,42			AuraPair43		>,44		sc_finality_grandpa::LinkHalf<Block, FullClient, FullSelectChain>,45		Option<TelemetrySpan>,46	)47>, ServiceError> {48	if config.keystore_remote.is_some() {49		return Err(ServiceError::Other(50			format!("Remote Keystores are not supported.")))51	}52	let inherent_data_providers = sp_inherents::InherentDataProviders::new();5354	let (client, backend, keystore_container, task_manager, telemetry_span) =55		sc_service::new_full_parts::<Block, RuntimeApi, Executor>(&config)?;56	let client = Arc::new(client);5758	let select_chain = sc_consensus::LongestChain::new(backend.clone());5960	let transaction_pool = sc_transaction_pool::BasicPool::new_full(61		config.transaction_pool.clone(),62		config.prometheus_registry(),63		task_manager.spawn_handle(),64		client.clone(),65	);6667	let (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import(68		client.clone(), &(client.clone() as Arc<_>), select_chain.clone(),69	)?;7071	let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(72		grandpa_block_import.clone(), client.clone(),73	);7475	let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _, _>(76		sc_consensus_aura::slot_duration(&*client)?,77		aura_block_import.clone(),78		Some(Box::new(grandpa_block_import.clone())),79		client.clone(),80		inherent_data_providers.clone(),81		&task_manager.spawn_handle(),82		config.prometheus_registry(),83		sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),84	)?;8586	Ok(sc_service::PartialComponents {87		client,88		backend,89		task_manager,90		import_queue,91		keystore_container,92		select_chain,93		transaction_pool,94		inherent_data_providers,95		other: (aura_block_import, grandpa_link, telemetry_span),96	})97}9899fn remote_keystore(_url: &String) -> Result<Arc<LocalKeystore>, &'static str> {100	// FIXME: here would the concrete keystore be built,101	//        must return a concrete type (NOT `LocalKeystore`) that102	//        implements `CryptoStore` and `SyncCryptoStore`103	Err("Remote Keystore not supported.")104}105106/// Builds a new service for a full client.107pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError> {108	let sc_service::PartialComponents {109		client,110		backend,111		mut task_manager,112		import_queue,113		mut keystore_container,114		select_chain,115		transaction_pool,116		inherent_data_providers,117		other: (block_import, grandpa_link, telemetry_span),118	} = new_partial(&config)?;119120	if let Some(url) = &config.keystore_remote {121		match remote_keystore(url) {122			Ok(k) => keystore_container.set_remote_keystore(k),123			Err(e) => {124				return Err(ServiceError::Other(125					format!("Error hooking up remote keystore for {}: {}", url, e)))126			}127		};128	}129130	config.network.extra_sets.push(sc_finality_grandpa::grandpa_peers_set_config());131132	let (network, network_status_sinks, system_rpc_tx, network_starter) =133		sc_service::build_network(sc_service::BuildNetworkParams {134			config: &config,135			client: client.clone(),136			transaction_pool: transaction_pool.clone(),137			spawn_handle: task_manager.spawn_handle(),138			import_queue,139			on_demand: None,140			block_announce_validator_builder: None,141		})?;142143	if config.offchain_worker.enabled {144		sc_service::build_offchain_workers(145			&config, backend.clone(), task_manager.spawn_handle(), client.clone(), network.clone(),146		);147	}148149	let role = config.role.clone();150	let force_authoring = config.force_authoring;151	let backoff_authoring_blocks: Option<()> = None;152	let name = config.network.node_name.clone();153	let enable_grandpa = !config.disable_grandpa;154	let prometheus_registry = config.prometheus_registry().cloned();155156	let rpc_extensions_builder = {157		let client = client.clone();158		let pool = transaction_pool.clone();159160		Box::new(move |deny_unsafe, _| {161			let deps = crate::rpc::FullDeps {162				client: client.clone(),163				pool: pool.clone(),164				deny_unsafe,165			};166167			crate::rpc::create_full(deps)168		})169	};170171	let (_rpc_handlers, telemetry_connection_notifier) = sc_service::spawn_tasks(172		sc_service::SpawnTasksParams {173			network: network.clone(),174			client: client.clone(),175			keystore: keystore_container.sync_keystore(),176			task_manager: &mut task_manager,177			transaction_pool: transaction_pool.clone(),178			rpc_extensions_builder,179			on_demand: None,180			remote_blockchain: None,181			backend,182			network_status_sinks,183			system_rpc_tx,184			config,185			telemetry_span,186		},187	)?;188189	if role.is_authority() {190		let proposer = sc_basic_authorship::ProposerFactory::new(191			task_manager.spawn_handle(),192			client.clone(),193			transaction_pool,194			prometheus_registry.as_ref(),195		);196197		let can_author_with =198			sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());199200		let aura = sc_consensus_aura::start_aura::<_, _, _, _, _, AuraPair, _, _, _,_>(201			sc_consensus_aura::slot_duration(&*client)?,202			client.clone(),203			select_chain,204			block_import,205			proposer,206			network.clone(),207			inherent_data_providers.clone(),208			force_authoring,209			backoff_authoring_blocks,210			keystore_container.sync_keystore(),211			can_author_with,212		)?;213214		// the AURA authoring task is considered essential, i.e. if it215		// fails we take down the service with it.216		task_manager.spawn_essential_handle().spawn_blocking("aura", aura);217	}218219	// if the node isn't actively participating in consensus then it doesn't220	// need a keystore, regardless of which protocol we use below.221	let keystore = if role.is_authority() {222		Some(keystore_container.sync_keystore())223	} else {224		None225	};226227	let grandpa_config = sc_finality_grandpa::Config {228		// FIXME #1578 make this available through chainspec229		gossip_duration: Duration::from_millis(333),230		justification_period: 512,231		name: Some(name),232		observer_enabled: false,233		keystore,234		is_authority: role.is_network_authority(),235	};236237	if enable_grandpa {238		// start the full GRANDPA voter239		// NOTE: non-authorities could run the GRANDPA observer protocol, but at240		// this point the full voter should provide better guarantees of block241		// and vote data availability than the observer. The observer has not242		// been tested extensively yet and having most nodes in a network run it243		// could lead to finality stalls.244		let grandpa_config = sc_finality_grandpa::GrandpaParams {245			config: grandpa_config,246			link: grandpa_link,247			network,248			telemetry_on_connect: telemetry_connection_notifier.map(|x| x.on_connect_stream()),249			voting_rule: sc_finality_grandpa::VotingRulesBuilder::default().build(),250			prometheus_registry,251			shared_voter_state: SharedVoterState::empty(),252		};253254		// the GRANDPA voter task is considered infallible, i.e.255		// if it fails we take down the service with it.256		task_manager.spawn_essential_handle().spawn_blocking(257			"grandpa-voter",258			sc_finality_grandpa::run_grandpa_voter(grandpa_config)?259		);260	}261262	network_starter.start_network();263	Ok(task_manager)264}265266/// Builds a new service for a light client.267pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError> {268	let (client, backend, keystore_container, mut task_manager, on_demand, telemetry_span) =269		sc_service::new_light_parts::<Block, RuntimeApi, Executor>(&config)?;270271	config.network.extra_sets.push(sc_finality_grandpa::grandpa_peers_set_config());272273	let select_chain = sc_consensus::LongestChain::new(backend.clone());274275	let transaction_pool = Arc::new(sc_transaction_pool::BasicPool::new_light(276		config.transaction_pool.clone(),277		config.prometheus_registry(),278		task_manager.spawn_handle(),279		client.clone(),280		on_demand.clone(),281	));282283	let (grandpa_block_import, _) = sc_finality_grandpa::block_import(284		client.clone(),285		&(client.clone() as Arc<_>),286		select_chain.clone(),287	)?;288289	let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(290		grandpa_block_import.clone(),291		client.clone(),292	);293294	let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _, _>(295		sc_consensus_aura::slot_duration(&*client)?,296		aura_block_import,297		Some(Box::new(grandpa_block_import)),298		client.clone(),299		InherentDataProviders::new(),300		&task_manager.spawn_handle(),301		config.prometheus_registry(),302		sp_consensus::NeverCanAuthor,303	)?;304305	let (network, network_status_sinks, system_rpc_tx, network_starter) =306		sc_service::build_network(sc_service::BuildNetworkParams {307			config: &config,308			client: client.clone(),309			transaction_pool: transaction_pool.clone(),310			spawn_handle: task_manager.spawn_handle(),311			import_queue,312			on_demand: Some(on_demand.clone()),313			block_announce_validator_builder: None,314		})?;315316	if config.offchain_worker.enabled {317		sc_service::build_offchain_workers(318			&config, backend.clone(), task_manager.spawn_handle(), client.clone(), network.clone(),319		);320	}321322	sc_service::spawn_tasks(sc_service::SpawnTasksParams {323		remote_blockchain: Some(backend.remote_blockchain()),324		transaction_pool,325		task_manager: &mut task_manager,326		on_demand: Some(on_demand),327		rpc_extensions_builder: Box::new(|_, _| ()),328		config,329		client,330		keystore: keystore_container.sync_keystore(),331		backend,332		network,333		network_status_sinks,334		system_rpc_tx,335		telemetry_span,336	})?;337338	network_starter.start_network();339340	Ok(task_manager)341}