lib.rs 22.2 KB
Newer Older
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// This file is part of Polkadot.

// Polkadot 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.

// Polkadot 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 Polkadot.  If not, see <http://www.gnu.org/licenses/>.

17
//! Polkadot service. Specialized wrapper over substrate service.
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
18

19
pub mod chain_spec;
20
mod grandpa_support;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
21

22
use sc_client::LongestChain;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
23
use std::sync::Arc;
24
use std::time::Duration;
25
use polkadot_primitives::{parachain, Hash, BlockId, AccountId, Nonce, Balance};
Ashley's avatar
Ashley committed
26
27
#[cfg(feature = "full-node")]
use polkadot_network::{legacy::gossip::Known, protocol as network_protocol};
28
use service::{error::Error as ServiceError, ServiceBuilder};
29
use grandpa::{self, FinalityProofProvider as GrandpaFinalityProofProvider};
30
use inherents::InherentDataProviders;
31
use sc_executor::native_executor_instance;
32
use log::info;
33
34
35
pub use service::{
	AbstractService, Roles, PruningMode, TransactionPoolOptions, Error, RuntimeGenesis, ServiceBuilderCommand,
	TFullClient, TLightClient, TFullBackend, TLightBackend, TFullCallExecutor, TLightCallExecutor,
Gavin Wood's avatar
Gavin Wood committed
36
	Configuration, ChainSpec,
37
};
Cecile Tonglet's avatar
Cecile Tonglet committed
38
pub use service::config::{DatabaseConfig, PrometheusConfig};
39
pub use sc_executor::NativeExecutionDispatch;
40
41
42
pub use sc_client::{ExecutionStrategy, CallExecutor, Client};
pub use sc_client_api::backend::Backend;
pub use sp_api::{Core as CoreApi, ConstructRuntimeApi, ProvideRuntimeApi, StateBackend};
43
pub use sp_runtime::traits::{HashFor, NumberFor};
44
pub use consensus_common::SelectChain;
45
pub use polkadot_primitives::parachain::{CollatorId, ParachainHost};
46
pub use polkadot_primitives::Block;
Gavin Wood's avatar
Gavin Wood committed
47
pub use sp_runtime::traits::{Block as BlockT, self as runtime_traits, BlakeTwo256};
Gavin Wood's avatar
Gavin Wood committed
48
pub use chain_spec::{PolkadotChainSpec, KusamaChainSpec};
49
#[cfg(not(target_os = "unknown"))]
50
pub use consensus::run_validation_worker;
51
52
53
pub use codec::Codec;
pub use polkadot_runtime;
pub use kusama_runtime;
Gavin Wood's avatar
Gavin Wood committed
54
use prometheus_endpoint::Registry;
55

56
57
58
native_executor_instance!(
	pub PolkadotExecutor,
	polkadot_runtime::api::dispatch,
59
60
	polkadot_runtime::native_version,
	frame_benchmarking::benchmarking::HostFunctions,
61
62
63
64
65
);

native_executor_instance!(
	pub KusamaExecutor,
	kusama_runtime::api::dispatch,
66
67
	kusama_runtime::native_version,
	frame_benchmarking::benchmarking::HostFunctions,
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
);

/// A set of APIs that polkadot-like runtimes must implement.
pub trait RuntimeApiCollection<Extrinsic: codec::Codec + Send + Sync + 'static> :
	sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
	+ sp_api::ApiExt<Block, Error = sp_blockchain::Error>
	+ babe_primitives::BabeApi<Block>
	+ ParachainHost<Block>
	+ sp_block_builder::BlockBuilder<Block>
	+ system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce>
	+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance, Extrinsic>
	+ sp_api::Metadata<Block>
	+ sp_offchain::OffchainWorkerApi<Block>
	+ sp_session::SessionKeys<Block>
	+ authority_discovery_primitives::AuthorityDiscoveryApi<Block>
where
	Extrinsic: RuntimeExtrinsic,
Gavin Wood's avatar
Gavin Wood committed
85
	<Self as sp_api::ApiExt<Block>>::StateBackend: sp_api::StateBackend<BlakeTwo256>,
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
{}

impl<Api, Extrinsic> RuntimeApiCollection<Extrinsic> for Api
where
	Api:
	sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
	+ sp_api::ApiExt<Block, Error = sp_blockchain::Error>
	+ babe_primitives::BabeApi<Block>
	+ ParachainHost<Block>
	+ sp_block_builder::BlockBuilder<Block>
	+ system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce>
	+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance, Extrinsic>
	+ sp_api::Metadata<Block>
	+ sp_offchain::OffchainWorkerApi<Block>
	+ sp_session::SessionKeys<Block>
	+ authority_discovery_primitives::AuthorityDiscoveryApi<Block>,
	Extrinsic: RuntimeExtrinsic,
Gavin Wood's avatar
Gavin Wood committed
103
	<Self as sp_api::ApiExt<Block>>::StateBackend: sp_api::StateBackend<BlakeTwo256>,
104
105
{}

106
pub trait RuntimeExtrinsic: codec::Codec + Send + Sync + 'static {}
107

108
impl<E> RuntimeExtrinsic for E where E: codec::Codec + Send + Sync + 'static {}
109
110
111
112
113
114
115

/// Can be called for a `Configuration` to check if it is a configuration for the `Kusama` network.
pub trait IsKusama {
	/// Returns if this is a configuration for the `Kusama` network.
	fn is_kusama(&self) -> bool;
}

Cecile Tonglet's avatar
Cecile Tonglet committed
116
impl IsKusama for Box<dyn ChainSpec> {
117
	fn is_kusama(&self) -> bool {
Gavin Wood's avatar
Gavin Wood committed
118
		self.id().starts_with("kusama") || self.id().starts_with("ksm")
119
120
	}
}
121

122
123
124
125
126
127
128
129
130
// If we're using prometheus, use a registry with a prefix of `polkadot`.
fn set_prometheus_registry(config: &mut Configuration) -> Result<(), ServiceError> {
	if let Some(PrometheusConfig { registry, .. }) = config.prometheus_config.as_mut() {
		*registry = Registry::new_custom(Some("polkadot".into()), None)?;
	}

	Ok(())
}

131
132
133
134
135
/// Starts a `ServiceBuilder` for a full service.
///
/// Use this macro if you don't actually need the full service, but just the builder in order to
/// be able to perform chain operations.
macro_rules! new_full_start {
136
	($config:expr, $runtime:ty, $executor:ty) => {{
137
138
		set_prometheus_registry(&mut $config)?;

139
140
141
		let mut import_setup = None;
		let inherent_data_providers = inherents::InherentDataProviders::new();
		let builder = service::ServiceBuilder::new_full::<
142
			Block, $runtime, $executor
143
		>($config)?
Gavin Wood's avatar
Gavin Wood committed
144
			.with_select_chain(|_, backend| {
145
				Ok(sc_client::LongestChain::new(backend.clone()))
146
			})?
Gavin Wood's avatar
Gavin Wood committed
147
			.with_transaction_pool(|config, client, _fetcher| {
148
				let pool_api = sc_transaction_pool::FullChainApi::new(client.clone());
149
				let pool = sc_transaction_pool::BasicPool::new(config, std::sync::Arc::new(pool_api));
Gavin Wood's avatar
Gavin Wood committed
150
				Ok(pool)
Gavin Wood's avatar
Gavin Wood committed
151
			})?
152
			.with_import_queue(|config, client, mut select_chain, _| {
153
154
				let select_chain = select_chain.take()
					.ok_or_else(|| service::Error::SelectChainRequired)?;
155

Cecile Tonglet's avatar
Cecile Tonglet committed
156
				let grandpa_hard_forks = if config.chain_spec.is_kusama() {
157
158
159
160
161
					grandpa_support::kusama_hard_forks()
				} else {
					Vec::new()
				};

162
				let (grandpa_block_import, grandpa_link) =
163
164
165
166
167
					grandpa::block_import_with_authority_set_hard_forks(
						client.clone(),
						&(client.clone() as Arc<_>),
						select_chain,
						grandpa_hard_forks,
thiolliere's avatar
thiolliere committed
168
					)?;
169

170
171
172
				let justification_import = grandpa_block_import.clone();

				let (block_import, babe_link) = babe::block_import(
173
174
175
					babe::Config::get_or_compute(&*client)?,
					grandpa_block_import,
					client.clone(),
176
177
				)?;

178
				let import_queue = babe::import_queue(
179
180
181
182
183
184
					babe_link.clone(),
					block_import.clone(),
					Some(Box::new(justification_import)),
					None,
					client,
					inherent_data_providers.clone(),
185
				)?;
186

187
				import_setup = Some((block_import, grandpa_link, babe_link));
188
				Ok(import_queue)
189
			})?
190
191
			.with_rpc_extensions(|builder| -> Result<polkadot_rpc::RpcExtension, _> {
				Ok(polkadot_rpc::create_full(builder.client().clone(), builder.pool()))
192
			})?;
193

194
		(builder, import_setup, inherent_data_providers)
195
196
	}}
}
197

198
/// Builds a new object suitable for chain operations.
199
pub fn new_chain_ops<Runtime, Dispatch, Extrinsic>(mut config: Configuration)
200
	-> Result<impl ServiceBuilderCommand<Block=Block>, ServiceError>
201
202
where
	Runtime: ConstructRuntimeApi<Block, service::TFullClient<Block, Runtime, Dispatch>> + Send + Sync + 'static,
203
	Runtime::RuntimeApi:
204
	RuntimeApiCollection<Extrinsic, StateBackend = sc_client_api::StateBackendFor<TFullBackend<Block>, Block>>,
205
206
	Dispatch: NativeExecutionDispatch + 'static,
	Extrinsic: RuntimeExtrinsic,
Gavin Wood's avatar
Gavin Wood committed
207
	<Runtime::RuntimeApi as sp_api::ApiExt<Block>>::StateBackend: sp_api::StateBackend<BlakeTwo256>,
208
{
209
	config.keystore = service::config::KeystoreConfig::InMemory;
210
211
212
213
	Ok(new_full_start!(config, Runtime, Dispatch).0)
}

/// Create a new Polkadot service for a full node.
Ashley's avatar
Ashley committed
214
#[cfg(feature = "full-node")]
Gavin Wood's avatar
Gavin Wood committed
215
216
217
218
219
220
pub fn polkadot_new_full(
	config: Configuration,
	collating_for: Option<(CollatorId, parachain::Id)>,
	max_block_data_size: Option<u64>,
	authority_discovery_enabled: bool,
	slot_duration: u64,
221
	grandpa_pause: Option<(u32, u32)>,
Gavin Wood's avatar
Gavin Wood committed
222
)
223
224
225
226
227
228
229
230
231
232
	-> Result<(
		impl AbstractService<
			Block = Block,
			RuntimeApi = polkadot_runtime::RuntimeApi,
			Backend = TFullBackend<Block>,
			SelectChain = LongestChain<TFullBackend<Block>, Block>,
			CallExecutor = TFullCallExecutor<Block, PolkadotExecutor>,
		>,
		FullNodeHandles,
	), ServiceError>
233
{
234
235
236
237
238
239
240
241
	new_full(
		config,
		collating_for,
		max_block_data_size,
		authority_discovery_enabled,
		slot_duration,
		grandpa_pause,
	)
242
243
244
}

/// Create a new Kusama service for a full node.
Ashley's avatar
Ashley committed
245
#[cfg(feature = "full-node")]
Gavin Wood's avatar
Gavin Wood committed
246
247
248
249
250
251
pub fn kusama_new_full(
	config: Configuration,
	collating_for: Option<(CollatorId, parachain::Id)>,
	max_block_data_size: Option<u64>,
	authority_discovery_enabled: bool,
	slot_duration: u64,
252
	grandpa_pause: Option<(u32, u32)>,
Gavin Wood's avatar
Gavin Wood committed
253
)
254
255
256
257
258
259
260
261
262
263
	-> Result<(
		impl AbstractService<
			Block = Block,
			RuntimeApi = kusama_runtime::RuntimeApi,
			Backend = TFullBackend<Block>,
			SelectChain = LongestChain<TFullBackend<Block>, Block>,
			CallExecutor = TFullCallExecutor<Block, KusamaExecutor>,
		>,
		FullNodeHandles,
	), ServiceError>
264
{
265
266
267
268
269
270
271
272
	new_full(
		config,
		collating_for,
		max_block_data_size,
		authority_discovery_enabled,
		slot_duration,
		grandpa_pause,
	)
273
}
274

275
276
/// Handles to other sub-services that full nodes instantiate, which consumers
/// of the node may use.
Ashley's avatar
Ashley committed
277
#[cfg(feature = "full-node")]
278
279
280
281
282
pub struct FullNodeHandles {
	/// A handle to the Polkadot networking protocol.
	pub polkadot_network: Option<network_protocol::Service>,
}

283
/// Builds a new service for a full client.
Ashley's avatar
Ashley committed
284
#[cfg(feature = "full-node")]
Gavin Wood's avatar
Gavin Wood committed
285
pub fn new_full<Runtime, Dispatch, Extrinsic>(
286
	mut config: Configuration,
Gavin Wood's avatar
Gavin Wood committed
287
288
289
290
	collating_for: Option<(CollatorId, parachain::Id)>,
	max_block_data_size: Option<u64>,
	authority_discovery_enabled: bool,
	slot_duration: u64,
291
	grandpa_pause: Option<(u32, u32)>,
Gavin Wood's avatar
Gavin Wood committed
292
)
293
294
295
296
297
298
299
300
301
302
	-> Result<(
		impl AbstractService<
			Block = Block,
			RuntimeApi = Runtime,
			Backend = TFullBackend<Block>,
			SelectChain = LongestChain<TFullBackend<Block>, Block>,
			CallExecutor = TFullCallExecutor<Block, Dispatch>,
		>,
		FullNodeHandles,
	), ServiceError>
303
304
	where
		Runtime: ConstructRuntimeApi<Block, service::TFullClient<Block, Runtime, Dispatch>> + Send + Sync + 'static,
305
306
		Runtime::RuntimeApi:
			RuntimeApiCollection<Extrinsic, StateBackend = sc_client_api::StateBackendFor<TFullBackend<Block>, Block>>,
307
308
		Dispatch: NativeExecutionDispatch + 'static,
		Extrinsic: RuntimeExtrinsic,
309
		// Rust bug: https://github.com/rust-lang/rust/issues/24159
Gavin Wood's avatar
Gavin Wood committed
310
		<Runtime::RuntimeApi as sp_api::ApiExt<Block>>::StateBackend: sp_api::StateBackend<BlakeTwo256>,
311
{
312
	use sc_network::Event;
313
	use sc_client_api::ExecutorProvider;
Gavin Wood's avatar
Gavin Wood committed
314
	use futures::stream::StreamExt;
315

Gavin Wood's avatar
Gavin Wood committed
316
	let is_collator = collating_for.is_some();
317
	let is_authority = config.roles.is_authority() && !is_collator;
Gavin Wood's avatar
Gavin Wood committed
318
	let force_authoring = config.force_authoring;
Gavin Wood's avatar
Gavin Wood committed
319
	let max_block_data_size = max_block_data_size;
Cecile Tonglet's avatar
Cecile Tonglet committed
320
	let db_path = if let DatabaseConfig::Path { ref path, .. } = config.database {
Gavin Wood's avatar
Gavin Wood committed
321
322
323
324
		path.clone()
	} else {
		return Err("Starting a Polkadot service with a custom database isn't supported".to_string().into());
	};
Gavin Wood's avatar
Gavin Wood committed
325
	let disable_grandpa = config.disable_grandpa;
Cecile Tonglet's avatar
Cecile Tonglet committed
326
	let name = config.network.node_name.clone();
Gavin Wood's avatar
Gavin Wood committed
327
	let authority_discovery_enabled = authority_discovery_enabled;
Gavin Wood's avatar
Gavin Wood committed
328
	let sentry_nodes = config.network.sentry_nodes.clone();
Gavin Wood's avatar
Gavin Wood committed
329
	let slot_duration = slot_duration;
Gavin Wood's avatar
Gavin Wood committed
330

Gavin Wood's avatar
Gavin Wood committed
331
332
333
334
335
	// sentry nodes announce themselves as authorities to the network
	// and should run the same protocols authorities do, but it should
	// never actively participate in any consensus process.
	let participates_in_consensus = is_authority && !config.sentry_mode;

336
	let (builder, mut import_setup, inherent_data_providers) = new_full_start!(config, Runtime, Dispatch);
337

338
339
	let backend = builder.backend().clone();

340
	let service = builder
341
342
343
344
		.with_finality_proof_provider(|client, backend| {
			let provider = client as Arc<dyn grandpa::StorageAndProofProvider<_, _>>;
			Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, provider)) as _)
		})?
345
346
		.build()?;

André Silva's avatar
André Silva committed
347
	let (block_import, link_half, babe_link) = import_setup.take()
348
349
350
351
		.expect("Link Half and Block Import are present for Full Services or setup failed before. qed");

	let client = service.client();
	let known_oracle = client.clone();
352
353

	let mut handles = FullNodeHandles { polkadot_network: None };
354
355
356
357
	let select_chain = if let Some(select_chain) = service.select_chain() {
		select_chain
	} else {
		info!("The node cannot start as an authority because it can't select chain.");
358
		return Ok((service, handles));
359
360
	};
	let gossip_validator_select_chain = select_chain.clone();
361
362

	let is_known = move |block_hash: &Hash| {
363
		use consensus_common::BlockStatus;
364
365
366
367
368
369
370
371
372
373
374
375

		match known_oracle.block_status(&BlockId::hash(*block_hash)) {
			Err(_) | Ok(BlockStatus::Unknown) | Ok(BlockStatus::Queued) => None,
			Ok(BlockStatus::KnownBad) => Some(Known::Bad),
			Ok(BlockStatus::InChainWithState) | Ok(BlockStatus::InChainPruned) => {
				match gossip_validator_select_chain.leaves() {
					Err(_) => None,
					Ok(leaves) => if leaves.contains(block_hash) {
						Some(Known::Leaf)
					} else {
						Some(Known::Old)
					},
376
				}
thiolliere's avatar
thiolliere committed
377
			}
378
379
380
		}
	};

381
	let polkadot_network_service = network_protocol::start(
382
		service.network(),
383
384
385
		network_protocol::Config {
			collating_for,
		},
386
		(is_known, client.clone()),
387
388
389
		client.clone(),
		service.spawn_task_handle(),
	).map_err(|e| format!("Could not spawn network worker: {:?}", e))?;
390

Gavin Wood's avatar
Gavin Wood committed
391
	if participates_in_consensus {
392
		let availability_store = {
393
394
			use std::path::PathBuf;

Gavin Wood's avatar
Gavin Wood committed
395
			let mut path = PathBuf::from(db_path);
396
397
			path.push("availability");

398
399
			#[cfg(not(target_os = "unknown"))]
			{
400
				av_store::Store::new(
401
402
403
404
405
					::av_store::Config {
						cache_size: None,
						path,
					},
					polkadot_network_service.clone(),
406
				)?
407
408
409
410
			}

			#[cfg(target_os = "unknown")]
			av_store::Store::new_in_memory(gossip)
411
412
		};

413
		polkadot_network_service.register_availability_store(availability_store.clone());
414
415
416

		let (validation_service_handle, validation_service) = consensus::ServiceBuilder {
			client: client.clone(),
417
418
			network: polkadot_network_service.clone(),
			collators: polkadot_network_service.clone(),
419
			spawner: service.spawn_task_handle(),
420
421
422
423
424
425
			availability_store: availability_store.clone(),
			select_chain: select_chain.clone(),
			keystore: service.keystore(),
			max_block_data_size,
		}.build();

Gavin Wood's avatar
Gavin Wood committed
426
		service.spawn_essential_task("validation-service", Box::pin(validation_service));
427

428
429
430
		let proposer = consensus::ProposerFactory::new(
			client.clone(),
			service.transaction_pool(),
431
			validation_service_handle,
432
			slot_duration,
433
			backend,
434
435
436
		);

		let select_chain = service.select_chain().ok_or(ServiceError::SelectChainRequired)?;
437
438
		let can_author_with =
			consensus_common::CanAuthorWithNativeVersion::new(client.executor().clone());
439

440
441
442
		let block_import = availability_store.block_import(
			block_import,
			client.clone(),
443
			service.spawn_task_handle(),
444
445
446
			service.keystore(),
		)?;

447
448
449
450
451
452
453
454
		let babe_config = babe::BabeParams {
			keystore: service.keystore(),
			client,
			select_chain,
			block_import,
			env: proposer,
			sync_oracle: service.network(),
			inherent_data_providers: inherent_data_providers.clone(),
455
			force_authoring,
456
			babe_link,
457
			can_author_with,
458
459
		};

460
		let babe = babe::start_babe(babe_config)?;
Gavin Wood's avatar
Gavin Wood committed
461
		service.spawn_essential_task("babe", babe);
Gavin Wood's avatar
Gavin Wood committed
462
463

		if authority_discovery_enabled {
464
			let network = service.network();
465
			let network_event_stream = network.event_stream();
466
			let dht_event_stream = network_event_stream.filter_map(|e| async move { match e {
467
				Event::Dht(e) => Some(e),
468
				_ => None,
Gavin Wood's avatar
Gavin Wood committed
469
			}}).boxed();
Gavin Wood's avatar
Gavin Wood committed
470
471
			let authority_discovery = authority_discovery::AuthorityDiscovery::new(
				service.client(),
472
				network,
Gavin Wood's avatar
Gavin Wood committed
473
				sentry_nodes,
Gavin Wood's avatar
Gavin Wood committed
474
				service.keystore(),
Gavin Wood's avatar
Gavin Wood committed
475
				dht_event_stream,
Gavin Wood's avatar
Gavin Wood committed
476
				service.prometheus_registry(),
Gavin Wood's avatar
Gavin Wood committed
477
			);
Gavin Wood's avatar
Gavin Wood committed
478
			service.spawn_task("authority-discovery", authority_discovery);
Gavin Wood's avatar
Gavin Wood committed
479
		}
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
480
	}
481

Gavin Wood's avatar
Gavin Wood committed
482
483
484
	// if the node isn't actively participating in consensus then it doesn't
	// need a keystore, regardless of which protocol we use below.
	let keystore = if participates_in_consensus {
485
486
487
488
489
		Some(service.keystore())
	} else {
		None
	};

490
491
	let config = grandpa::Config {
		// FIXME substrate#1578 make this available through chainspec
492
		gossip_duration: Duration::from_millis(1000),
493
		justification_period: 512,
Gavin Wood's avatar
Gavin Wood committed
494
		name: Some(name),
Gavin Wood's avatar
Gavin Wood committed
495
		observer_enabled: false,
496
		keystore,
Gavin Wood's avatar
Gavin Wood committed
497
		is_authority,
498
499
	};

500
501
502
503
504
505
506
507
	let enable_grandpa = !disable_grandpa;
	if enable_grandpa {
		// start the full GRANDPA voter
		// NOTE: unlike in substrate we are currently running the full
		// GRANDPA voter protocol for all full nodes (regardless of whether
		// they're validators or not). at this point the full voter should
		// provide better guarantees of block and vote data availability than
		// the observer.
508
509
510
511
512
513
514
515
516
517
518
519

		// add a custom voting rule to temporarily stop voting for new blocks
		// after the given pause block is finalized and restarting after the
		// given delay.
		let voting_rule = match grandpa_pause {
			Some((block, delay)) => {
				info!("GRANDPA scheduled voting pause set for block #{} with a duration of {} blocks.",
					block,
					delay,
				);

				grandpa::VotingRulesBuilder::default()
520
					.add(grandpa_support::PauseAfterBlockFor(block, delay))
521
522
523
524
525
526
527
					.build()
			},
			None =>
				grandpa::VotingRulesBuilder::default()
					.build(),
		};

528
		let grandpa_config = grandpa::GrandpaParams {
529
			config,
530
531
532
533
			link: link_half,
			network: service.network(),
			inherent_data_providers: inherent_data_providers.clone(),
			telemetry_on_connect: Some(service.telemetry_on_connect_stream()),
534
			voting_rule,
Gavin Wood's avatar
Gavin Wood committed
535
			prometheus_registry: service.prometheus_registry(),
536
		};
Gavin Wood's avatar
Gavin Wood committed
537

538
		service.spawn_essential_task(
Gavin Wood's avatar
Gavin Wood committed
539
540
			"grandpa-voter",
			grandpa::run_grandpa_voter(grandpa_config)?
541
		);
542
543
544
545
546
547
	} else {
		grandpa::setup_disabled_grandpa(
			service.client(),
			&inherent_data_providers,
			service.network(),
		)?;
548
549
	}

550
551
	handles.polkadot_network = Some(polkadot_network_service);
	Ok((service, handles))
552
553
}

554
/// Create a new Polkadot service for a light client.
Gavin Wood's avatar
Gavin Wood committed
555
556
557
pub fn polkadot_new_light(
	config: Configuration,
)
558
559
560
561
562
563
564
565
	-> Result<impl AbstractService<
		Block = Block,
		RuntimeApi = polkadot_runtime::RuntimeApi,
		Backend = TLightBackend<Block>,
		SelectChain = LongestChain<TLightBackend<Block>, Block>,
		CallExecutor = TLightCallExecutor<Block, PolkadotExecutor>,
	>, ServiceError>
{
566
	new_light(config)
567
568
569
}

/// Create a new Kusama service for a light client.
Gavin Wood's avatar
Gavin Wood committed
570
571
572
pub fn kusama_new_light(
	config: Configuration,
)
573
574
575
576
577
578
579
580
	-> Result<impl AbstractService<
		Block = Block,
		RuntimeApi = kusama_runtime::RuntimeApi,
		Backend = TLightBackend<Block>,
		SelectChain = LongestChain<TLightBackend<Block>, Block>,
		CallExecutor = TLightCallExecutor<Block, KusamaExecutor>,
	>, ServiceError>
{
581
	new_light(config)
582
583
}

584
585
586
// We can't use service::TLightClient due to
// Rust bug: https://github.com/rust-lang/rust/issues/43580
type TLocalLightClient<Runtime, Dispatch> =  Client<
Gavin Wood's avatar
Gavin Wood committed
587
	sc_client::light::backend::Backend<sc_client_db::light::LightStorage<Block>, BlakeTwo256>,
588
	sc_client::light::call_executor::GenesisCallExecutor<
Gavin Wood's avatar
Gavin Wood committed
589
		sc_client::light::backend::Backend<sc_client_db::light::LightStorage<Block>, BlakeTwo256>,
590
591
592
		sc_client::LocalCallExecutor<
			sc_client::light::backend::Backend<
				sc_client_db::light::LightStorage<Block>,
Gavin Wood's avatar
Gavin Wood committed
593
				BlakeTwo256
594
595
596
597
598
599
600
601
			>,
			sc_executor::NativeExecutor<Dispatch>
		>
	>,
	Block,
	Runtime
>;

602
/// Builds a new service for a light client.
Gavin Wood's avatar
Gavin Wood committed
603
pub fn new_light<Runtime, Dispatch, Extrinsic>(
604
	mut config: Configuration,
Gavin Wood's avatar
Gavin Wood committed
605
)
606
	-> Result<impl AbstractService<
607
608
609
610
611
		Block = Block,
		RuntimeApi = Runtime,
		Backend = TLightBackend<Block>,
		SelectChain = LongestChain<TLightBackend<Block>, Block>,
		CallExecutor = TLightCallExecutor<Block, Dispatch>,
612
	>, ServiceError>
613
where
614
615
616
617
618
	Runtime: Send + Sync + 'static,
	Runtime::RuntimeApi: RuntimeApiCollection<
		Extrinsic,
		StateBackend = sc_client_api::StateBackendFor<TLightBackend<Block>, Block>
	>,
619
620
	Dispatch: NativeExecutionDispatch + 'static,
	Extrinsic: RuntimeExtrinsic,
621
622
623
624
	Runtime: sp_api::ConstructRuntimeApi<
		Block,
		TLocalLightClient<Runtime, Dispatch>,
	>,
625
{
626
627
	set_prometheus_registry(&mut config)?;

628
629
	let inherent_data_providers = InherentDataProviders::new();

630
	ServiceBuilder::new_light::<Block, Runtime, Dispatch>(config)?
Gavin Wood's avatar
Gavin Wood committed
631
632
		.with_select_chain(|_, backend| {
			Ok(LongestChain::new(backend.clone()))
633
		})?
Gavin Wood's avatar
Gavin Wood committed
634
635
636
		.with_transaction_pool(|config, client, fetcher| {
			let fetcher = fetcher
				.ok_or_else(|| "Trying to start light transaction pool without active fetcher")?;
637
			let pool_api = sc_transaction_pool::LightChainApi::new(client.clone(), fetcher.clone());
Gavin Wood's avatar
Gavin Wood committed
638
			let pool = sc_transaction_pool::BasicPool::with_revalidation_type(
639
				config, Arc::new(pool_api), sc_transaction_pool::RevalidationType::Light,
Gavin Wood's avatar
Gavin Wood committed
640
641
			);
			Ok(pool)
Gavin Wood's avatar
Gavin Wood committed
642
		})?
643
		.with_import_queue_and_fprb(|_config, client, backend, fetcher, _select_chain, _| {
thiolliere's avatar
thiolliere committed
644
			let fetch_checker = fetcher
645
646
				.map(|fetcher| fetcher.checker().clone())
				.ok_or_else(|| "Trying to start light import queue without active fetch checker")?;
Gavin Wood's avatar
Gavin Wood committed
647
			let grandpa_block_import = grandpa::light_block_import(
648
				client.clone(), backend, &(client.clone() as Arc<_>), Arc::new(fetch_checker)
649
650
			)?;

651
			let finality_proof_import = grandpa_block_import.clone();
652
653
654
			let finality_proof_request_builder =
				finality_proof_import.create_finality_proof_request_builder();

655
656
657
658
659
660
			let (babe_block_import, babe_link) = babe::block_import(
				babe::Config::get_or_compute(&*client)?,
				grandpa_block_import,
				client.clone(),
			)?;

661
			// FIXME: pruning task isn't started since light client doesn't do `AuthoritySetup`.
662
			let import_queue = babe::import_queue(
663
664
				babe_link,
				babe_block_import,
665
666
667
668
669
670
671
672
				None,
				Some(Box::new(finality_proof_import)),
				client,
				inherent_data_providers.clone(),
			)?;

			Ok((import_queue, finality_proof_request_builder))
		})?
673
674
675
676
		.with_finality_proof_provider(|client, backend| {
			let provider = client as Arc<dyn grandpa::StorageAndProofProvider<_, _>>;
			Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, provider)) as _)
		})?
677
		.with_rpc_extensions(|builder|
Gavin Wood's avatar
Gavin Wood committed
678
			-> Result<polkadot_rpc::RpcExtension, _> {
679
			let fetcher = builder.fetcher()
Gavin Wood's avatar
Gavin Wood committed
680
				.ok_or_else(|| "Trying to start node RPC without active fetcher")?;
681
			let remote_blockchain = builder.remote_backend()
Gavin Wood's avatar
Gavin Wood committed
682
				.ok_or_else(|| "Trying to start node RPC without active remote blockchain")?;
683
684

			Ok(polkadot_rpc::create_light(builder.client().clone(), remote_blockchain, fetcher, builder.pool()))
685
		})?
686
		.build()
687
}