git.delta.rocks / unique-network / refs/commits / 8b6fe6666d58

difftreelog

source

src/service.rs8.5 KiBsourcehistory
1//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.23use std::sync::Arc;4use std::time::Duration;5use sc_client::LongestChain;6use node_template_runtime::{self, GenesisConfig, opaque::Block, RuntimeApi};7use sc_service::{error::{Error as ServiceError}, AbstractService, Configuration, ServiceBuilder};8use sp_inherents::InherentDataProviders;9use sc_network::{construct_simple_protocol};10use sc_executor::native_executor_instance;11pub use sc_executor::NativeExecutor;12use sp_consensus_aura::sr25519::{AuthorityPair as AuraPair};13use grandpa::{self, FinalityProofProvider as GrandpaFinalityProofProvider};14use sc_basic_authority;1516// Our native executor instance.17native_executor_instance!(18	pub Executor,19	node_template_runtime::api::dispatch,20	node_template_runtime::native_version,21);2223construct_simple_protocol! {24	/// Demo protocol attachment for substrate.25	pub struct NodeProtocol where Block = Block { }26}2728/// Starts a `ServiceBuilder` for a full service.29///30/// Use this macro if you don't actually need the full service, but just the builder in order to31/// be able to perform chain operations.32macro_rules! new_full_start {33	($config:expr) => {{34		let mut import_setup = None;35		let inherent_data_providers = sp_inherents::InherentDataProviders::new();3637		let builder = sc_service::ServiceBuilder::new_full::<38			node_template_runtime::opaque::Block, node_template_runtime::RuntimeApi, crate::service::Executor39		>($config)?40			.with_select_chain(|_config, backend| {41				Ok(sc_client::LongestChain::new(backend.clone()))42			})?43			.with_transaction_pool(|config, client, _fetcher| {44				let pool_api = sc_transaction_pool::FullChainApi::new(client.clone());45				let pool = sc_transaction_pool::BasicPool::new(config, pool_api);46				let maintainer = sc_transaction_pool::FullBasicPoolMaintainer::new(pool.pool().clone(), client);47				let maintainable_pool = sp_transaction_pool::MaintainableTransactionPool::new(pool, maintainer);48				Ok(maintainable_pool)49			})?50			.with_import_queue(|_config, client, mut select_chain, transaction_pool| {51				let select_chain = select_chain.take()52					.ok_or_else(|| sc_service::Error::SelectChainRequired)?;5354				let (grandpa_block_import, grandpa_link) =55					grandpa::block_import::<_, _, _, node_template_runtime::RuntimeApi, _>(56						client.clone(), &*client, select_chain57					)?;5859				let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(60					grandpa_block_import.clone(), client.clone(),61				);6263				let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _>(64					sc_consensus_aura::SlotDuration::get_or_compute(&*client)?,65					aura_block_import,66					Some(Box::new(grandpa_block_import.clone())),67					None,68					client,69					inherent_data_providers.clone(),70					Some(transaction_pool),71				)?;7273				import_setup = Some((grandpa_block_import, grandpa_link));7475				Ok(import_queue)76			})?;7778		(builder, import_setup, inherent_data_providers)79	}}80}8182/// Builds a new service for a full client.83pub fn new_full<C: Send + Default + 'static>(config: Configuration<C, GenesisConfig>)84	-> Result<impl AbstractService, ServiceError>85{86	let is_authority = config.roles.is_authority();87	let force_authoring = config.force_authoring;88	let name = config.name.clone();89	let disable_grandpa = config.disable_grandpa;9091	// sentry nodes announce themselves as authorities to the network92	// and should run the same protocols authorities do, but it should93	// never actively participate in any consensus process.94	let participates_in_consensus = is_authority && !config.sentry_mode;9596	let (builder, mut import_setup, inherent_data_providers) = new_full_start!(config);9798	let (block_import, grandpa_link) =99		import_setup.take()100			.expect("Link Half and Block Import are present for Full Services or setup failed before. qed");101102	let service = builder.with_network_protocol(|_| Ok(NodeProtocol::new()))?103		.with_finality_proof_provider(|client, backend|104			Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, client)) as _)105		)?106		.build()?;107108	if participates_in_consensus {109		let proposer = sc_basic_authority::ProposerFactory {110			client: service.client(),111			transaction_pool: service.transaction_pool(),112		};113114		let client = service.client();115		let select_chain = service.select_chain()116			.ok_or(ServiceError::SelectChainRequired)?;117118		let can_author_with =119			sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());120121		let aura = sc_consensus_aura::start_aura::<_, _, _, _, _, AuraPair, _, _, _, _>(122			sc_consensus_aura::SlotDuration::get_or_compute(&*client)?,123			client,124			select_chain,125			block_import,126			proposer,127			service.network(),128			inherent_data_providers.clone(),129			force_authoring,130			service.keystore(),131			can_author_with,132		)?;133134		// the AURA authoring task is considered essential, i.e. if it135		// fails we take down the service with it.136		service.spawn_essential_task(aura);137	}138139	// if the node isn't actively participating in consensus then it doesn't140	// need a keystore, regardless of which protocol we use below.141	let keystore = if participates_in_consensus {142		Some(service.keystore())143	} else {144		None145	};146147	let grandpa_config = grandpa::Config {148		// FIXME #1578 make this available through chainspec149		gossip_duration: Duration::from_millis(333),150		justification_period: 512,151		name: Some(name),152		observer_enabled: true,153		keystore,154		is_authority,155	};156157	match (is_authority, disable_grandpa) {158		(false, false) => {159			// start the lightweight GRANDPA observer160			service.spawn_task(grandpa::run_grandpa_observer(161				grandpa_config,162				grandpa_link,163				service.network(),164				service.on_exit(),165				service.spawn_task_handle(),166			)?);167		},168		(true, false) => {169			// start the full GRANDPA voter170			let voter_config = grandpa::GrandpaParams {171				config: grandpa_config,172				link: grandpa_link,173				network: service.network(),174				inherent_data_providers: inherent_data_providers.clone(),175				on_exit: service.on_exit(),176				telemetry_on_connect: Some(service.telemetry_on_connect_stream()),177				voting_rule: grandpa::VotingRulesBuilder::default().build(),178				executor: service.spawn_task_handle(),179			};180181			// the GRANDPA voter task is considered infallible, i.e.182			// if it fails we take down the service with it.183			service.spawn_essential_task(grandpa::run_grandpa_voter(voter_config)?);184		},185		(_, true) => {186			grandpa::setup_disabled_grandpa(187				service.client(),188				&inherent_data_providers,189				service.network(),190			)?;191		},192	}193194	Ok(service)195}196197/// Builds a new service for a light client.198pub fn new_light<C: Send + Default + 'static>(config: Configuration<C, GenesisConfig>)199	-> Result<impl AbstractService, ServiceError>200{201	let inherent_data_providers = InherentDataProviders::new();202203	ServiceBuilder::new_light::<Block, RuntimeApi, Executor>(config)?204		.with_select_chain(|_config, backend| {205			Ok(LongestChain::new(backend.clone()))206		})?207		.with_transaction_pool(|config, client, fetcher| {208			let fetcher = fetcher209				.ok_or_else(|| "Trying to start light transaction pool without active fetcher")?;210			let pool_api = sc_transaction_pool::LightChainApi::new(client.clone(), fetcher.clone());211			let pool = sc_transaction_pool::BasicPool::new(config, pool_api);212			let maintainer = sc_transaction_pool::LightBasicPoolMaintainer::with_defaults(pool.pool().clone(), client, fetcher);213			let maintainable_pool = sp_transaction_pool::MaintainableTransactionPool::new(pool, maintainer);214			Ok(maintainable_pool)215		})?216		.with_import_queue_and_fprb(|_config, client, backend, fetcher, _select_chain, _tx_pool| {217			let fetch_checker = fetcher218				.map(|fetcher| fetcher.checker().clone())219				.ok_or_else(|| "Trying to start light import queue without active fetch checker")?;220			let grandpa_block_import = grandpa::light_block_import::<_, _, _, RuntimeApi>(221				client.clone(), backend, &*client.clone(), Arc::new(fetch_checker),222			)?;223			let finality_proof_import = grandpa_block_import.clone();224			let finality_proof_request_builder =225				finality_proof_import.create_finality_proof_request_builder();226227			let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, ()>(228				sc_consensus_aura::SlotDuration::get_or_compute(&*client)?,229				grandpa_block_import,230				None,231				Some(Box::new(finality_proof_import)),232				client,233				inherent_data_providers.clone(),234				None,235			)?;236237			Ok((import_queue, finality_proof_request_builder))238		})?239		.with_network_protocol(|_| Ok(NodeProtocol::new()))?240		.with_finality_proof_provider(|client, backend|241			Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, client)) as _)242		)?243		.build()244}