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;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
20

21
22
23
use futures::{
	FutureExt, TryFutureExt,
	task::{Spawn, SpawnError, FutureObj},
24
	compat::{Future01CompatExt, Stream01CompatExt},
25
};
26
use sc_client::LongestChain;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
27
use std::sync::Arc;
28
use std::time::Duration;
29
use polkadot_primitives::{parachain, Hash, BlockId, AccountId, Nonce, Balance};
30
use polkadot_network::{gossip::{self as network_gossip, Known}, validation::ValidationNetwork};
31
use service::{error::{Error as ServiceError}, ServiceBuilder};
32
use grandpa::{self, FinalityProofProvider as GrandpaFinalityProofProvider};
33
use inherents::InherentDataProviders;
34
use sc_executor::native_executor_instance;
35
use log::info;
36
37
38
39
pub use service::{
	AbstractService, Roles, PruningMode, TransactionPoolOptions, Error, RuntimeGenesis, ServiceBuilderCommand,
	TFullClient, TLightClient, TFullBackend, TLightBackend, TFullCallExecutor, TLightCallExecutor,
};
Gavin Wood's avatar
Gavin Wood committed
40
pub use service::config::{DatabaseConfig, full_version_from_strs};
41
pub use sc_executor::NativeExecutionDispatch;
42
43
44
45
pub use sc_client::{ExecutionStrategy, CallExecutor, Client};
pub use sc_client_api::backend::Backend;
pub use sp_api::{Core as CoreApi, ConstructRuntimeApi, ProvideRuntimeApi, StateBackend};
pub use sp_runtime::traits::HasherFor;
46
pub use consensus_common::SelectChain;
47
pub use polkadot_network::PolkadotProtocol;
48
pub use polkadot_primitives::parachain::{CollatorId, ParachainHost};
49
pub use polkadot_primitives::Block;
50
51
pub use sp_core::Blake2Hasher;
pub use sp_runtime::traits::{Block as BlockT, self as runtime_traits};
52
pub use sc_network::specialization::NetworkSpecialization;
53
pub use chain_spec::ChainSpec;
54
#[cfg(not(target_os = "unknown"))]
55
pub use consensus::run_validation_worker;
56
57
58
pub use codec::Codec;
pub use polkadot_runtime;
pub use kusama_runtime;
59

60
61
62
63
64
65
66
67
68
69
70
71
/// Wrap a futures01 executor as a futures03 spawn.
#[derive(Clone)]
pub struct WrappedExecutor<T>(pub T);

impl<T> Spawn for WrappedExecutor<T>
	where T: futures01::future::Executor<Box<dyn futures01::Future<Item=(),Error=()> + Send + 'static>>
{
	fn spawn_obj(&self, future: FutureObj<'static, ()>) -> Result<(), SpawnError> {
		self.0.execute(Box::new(future.map(Ok).compat()))
			.map_err(|_| SpawnError::shutdown())
	}
}
72
73
/// Polkadot-specific configuration.
pub struct CustomConfiguration {
74
	/// Set to `Some` with a collator `CollatorId` and desired parachain
75
	/// if the network protocol should be started in collator mode.
Gav Wood's avatar
Gav Wood committed
76
	pub collating_for: Option<(CollatorId, parachain::Id)>,
77

78
79
	/// Maximal `block_data` size.
	pub max_block_data_size: Option<u64>,
Gavin Wood's avatar
Gavin Wood committed
80
81
82

	/// Whether to enable or disable the authority discovery module.
	pub authority_discovery_enabled: bool,
83
84
85

	/// Milliseconds per block.
	pub slot_duration: u64,
86
87
}

88
89
90
/// Configuration type that is being used.
///
/// See [`ChainSpec`] for more information why Polkadot `GenesisConfig` is safe here.
91
92
93
94
95
pub type Configuration = service::Configuration<
	CustomConfiguration,
	polkadot_runtime::GenesisConfig,
	chain_spec::Extensions,
>;
96

97
98
99
100
impl Default for CustomConfiguration {
	fn default() -> Self {
		Self {
			collating_for: None,
101
			max_block_data_size: None,
Gavin Wood's avatar
Gavin Wood committed
102
			authority_discovery_enabled: false,
103
			slot_duration: 6000,
104
105
		}
	}
106
107
}

108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
native_executor_instance!(
	pub PolkadotExecutor,
	polkadot_runtime::api::dispatch,
	polkadot_runtime::native_version
);

native_executor_instance!(
	pub KusamaExecutor,
	kusama_runtime::api::dispatch,
	kusama_runtime::native_version
);

/// 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,
135
	<Self as sp_api::ApiExt<Block>>::StateBackend: sp_api::StateBackend<Blake2Hasher>,
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
{}

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,
153
	<Self as sp_api::ApiExt<Block>>::StateBackend: sp_api::StateBackend<Blake2Hasher>,
154
155
156
157
158
159
160
161
162
163
164
165
166
167
{}

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

impl<E> RuntimeExtrinsic for E where E: codec::Codec + Send + Sync + 'static
{}

/// 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;
}

168
impl IsKusama for ChainSpec {
169
	fn is_kusama(&self) -> bool {
170
		self.name().starts_with("Kusama")
171
172
	}
}
173

174
175
176
177
178
/// 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 {
179
	($config:expr, $runtime:ty, $executor:ty) => {{
180
181
182
		let mut import_setup = None;
		let inherent_data_providers = inherents::InherentDataProviders::new();
		let builder = service::ServiceBuilder::new_full::<
183
			Block, $runtime, $executor
184
		>($config)?
Gavin Wood's avatar
Gavin Wood committed
185
			.with_select_chain(|_, backend| {
186
				Ok(sc_client::LongestChain::new(backend.clone()))
187
			})?
Gavin Wood's avatar
Gavin Wood committed
188
			.with_transaction_pool(|config, client, _fetcher| {
189
190
191
192
				let pool_api = sc_transaction_pool::FullChainApi::new(client.clone());
				let pool = sc_transaction_pool::BasicPool::new(config, pool_api);
				let maintainer = sc_transaction_pool::FullBasicPoolMaintainer::new(pool.pool().clone(), client);
				let maintainable_pool = sp_transaction_pool::MaintainableTransactionPool::new(pool, maintainer);
Gavin Wood's avatar
Gavin Wood committed
193
194
				Ok(maintainable_pool)
			})?
195
			.with_import_queue(|_config, client, mut select_chain, _| {
196
197
				let select_chain = select_chain.take()
					.ok_or_else(|| service::Error::SelectChainRequired)?;
198
				let (grandpa_block_import, grandpa_link) =
199
					grandpa::block_import::<_, _, _, Runtime, _>(
200
						client.clone(), &*client, select_chain
thiolliere's avatar
thiolliere committed
201
					)?;
202
203
204
				let justification_import = grandpa_block_import.clone();

				let (block_import, babe_link) = babe::block_import(
205
206
207
208
					babe::Config::get_or_compute(&*client)?,
					grandpa_block_import,
					client.clone(),
					client.clone(),
209
210
				)?;

211
				let import_queue = babe::import_queue(
212
213
214
215
216
217
218
					babe_link.clone(),
					block_import.clone(),
					Some(Box::new(justification_import)),
					None,
					client.clone(),
					client,
					inherent_data_providers.clone(),
219
				)?;
220

221
				import_setup = Some((block_import, grandpa_link, babe_link));
222
				Ok(import_queue)
223
			})?
Gavin Wood's avatar
Gavin Wood committed
224
225
226
			.with_rpc_extensions(|client, pool, _backend, _fetcher, _remote_blockchain|
				-> Result<polkadot_rpc::RpcExtension, _> {
				Ok(polkadot_rpc::create_full(client, pool))
227
			})?;
228

229
		(builder, import_setup, inherent_data_providers)
230
231
	}}
}
232

233
/// Builds a new object suitable for chain operations.
234
pub fn new_chain_ops<Runtime, Dispatch, Extrinsic>(mut config: Configuration)
235
	-> Result<impl ServiceBuilderCommand<Block=Block>, ServiceError>
236
237
where
	Runtime: ConstructRuntimeApi<Block, service::TFullClient<Block, Runtime, Dispatch>> + Send + Sync + 'static,
238
	Runtime::RuntimeApi:
239
	RuntimeApiCollection<Extrinsic, StateBackend = sc_client_api::StateBackendFor<TFullBackend<Block>, Block>>,
240
241
	Dispatch: NativeExecutionDispatch + 'static,
	Extrinsic: RuntimeExtrinsic,
242
	<Runtime::RuntimeApi as sp_api::ApiExt<Block>>::StateBackend: sp_api::StateBackend<Blake2Hasher>,
243
{
244
	config.keystore = service::config::KeystoreConfig::InMemory;
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
	Ok(new_full_start!(config, Runtime, Dispatch).0)
}

/// Create a new Polkadot service for a full node.
pub fn polkadot_new_full(config: Configuration)
	-> Result<impl AbstractService<
		Block = Block,
		RuntimeApi = polkadot_runtime::RuntimeApi,
		NetworkSpecialization = PolkadotProtocol,
		Backend = TFullBackend<Block>,
		SelectChain = LongestChain<TFullBackend<Block>, Block>,
		CallExecutor = TFullCallExecutor<Block, PolkadotExecutor>,
	>, ServiceError>
{
	new_full(config)
}

/// Create a new Kusama service for a full node.
pub fn kusama_new_full(config: Configuration)
	-> Result<impl AbstractService<
		Block = Block,
		RuntimeApi = kusama_runtime::RuntimeApi,
		NetworkSpecialization = PolkadotProtocol,
		Backend = TFullBackend<Block>,
		SelectChain = LongestChain<TFullBackend<Block>, Block>,
		CallExecutor = TFullCallExecutor<Block, KusamaExecutor>,
	>, ServiceError>
{
	new_full(config)
274
}
275

276
/// Builds a new service for a full client.
277
pub fn new_full<Runtime, Dispatch, Extrinsic>(config: Configuration)
278
	-> Result<impl AbstractService<
279
280
281
282
283
284
		Block = Block,
		RuntimeApi = Runtime,
		NetworkSpecialization = PolkadotProtocol,
		Backend = TFullBackend<Block>,
		SelectChain = LongestChain<TFullBackend<Block>, Block>,
		CallExecutor = TFullCallExecutor<Block, Dispatch>,
285
	>, ServiceError>
286
287
	where
		Runtime: ConstructRuntimeApi<Block, service::TFullClient<Block, Runtime, Dispatch>> + Send + Sync + 'static,
288
289
		Runtime::RuntimeApi:
			RuntimeApiCollection<Extrinsic, StateBackend = sc_client_api::StateBackendFor<TFullBackend<Block>, Block>>,
290
291
		Dispatch: NativeExecutionDispatch + 'static,
		Extrinsic: RuntimeExtrinsic,
292
293
		// Rust bug: https://github.com/rust-lang/rust/issues/24159
		<Runtime::RuntimeApi as sp_api::ApiExt<Block>>::StateBackend: sp_api::StateBackend<Blake2Hasher>,
294
{
295
	use sc_network::Event;
Gavin Wood's avatar
Gavin Wood committed
296
	use futures::stream::StreamExt;
297

Gavin Wood's avatar
Gavin Wood committed
298
	let is_collator = config.custom.collating_for.is_some();
299
	let is_authority = config.roles.is_authority() && !is_collator;
Gavin Wood's avatar
Gavin Wood committed
300
301
	let force_authoring = config.force_authoring;
	let max_block_data_size = config.custom.max_block_data_size;
Gavin Wood's avatar
Gavin Wood committed
302
303
304
305
306
	let db_path = if let DatabaseConfig::Path { ref path, .. } = config.database {
		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
307
308
	let disable_grandpa = config.disable_grandpa;
	let name = config.name.clone();
Gavin Wood's avatar
Gavin Wood committed
309
	let authority_discovery_enabled = config.custom.authority_discovery_enabled;
Gavin Wood's avatar
Gavin Wood committed
310
	let sentry_nodes = config.network.sentry_nodes.clone();
311
	let slot_duration = config.custom.slot_duration;
Gavin Wood's avatar
Gavin Wood committed
312

Gavin Wood's avatar
Gavin Wood committed
313
314
315
316
317
	// 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;

318
	let (builder, mut import_setup, inherent_data_providers) = new_full_start!(config, Runtime, Dispatch);
319

320
321
	let backend = builder.backend().clone();

322
323
	let service = builder
		.with_network_protocol(|config| Ok(PolkadotProtocol::new(config.custom.collating_for.clone())))?
Gavin Wood's avatar
Gavin Wood committed
324
325
		.with_finality_proof_provider(|client, backend|
			Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, client)) as _)
326
327
328
		)?
		.build()?;

André Silva's avatar
André Silva committed
329
	let (block_import, link_half, babe_link) = import_setup.take()
330
331
332
333
334
335
336
337
338
339
340
		.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();
	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.");
		return Ok(service);
	};
	let gossip_validator_select_chain = select_chain.clone();
341
342

	let is_known = move |block_hash: &Hash| {
343
		use consensus_common::BlockStatus;
344
345
346
347
348
349
350
351
352
353
354
355

		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)
					},
356
				}
thiolliere's avatar
thiolliere committed
357
			}
358
359
360
		}
	};

361
	let mut gossip_validator = network_gossip::register_validator(
362
363
		service.network(),
		(is_known, client.clone()),
364
		&service.spawn_task_handle(),
365
366
	);

Gavin Wood's avatar
Gavin Wood committed
367
	if participates_in_consensus {
368
		let availability_store = {
369
370
			use std::path::PathBuf;

Gavin Wood's avatar
Gavin Wood committed
371
			let mut path = PathBuf::from(db_path);
372
373
			path.push("availability");

374
			let gossip = polkadot_network::AvailabilityNetworkShim(gossip_validator.clone());
375
376
377
378
379
380
381
382
383
384
385

			#[cfg(not(target_os = "unknown"))]
			{
				av_store::Store::new(::av_store::Config {
					cache_size: None,
					path,
				}, gossip)?
			}

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

388
389
390
391
392
393
394
		{
			let availability_store = availability_store.clone();
			service.network().with_spec(
				|spec, _ctx| spec.register_availability_store(availability_store)
			);
		}

395
396
397
398
399
		{
			let availability_store = availability_store.clone();
			gossip_validator.register_availability_store(availability_store);
		}

400
401
402
		// collator connections and validation network both fulfilled by this
		let validation_network = ValidationNetwork::new(
			gossip_validator,
403
			service.on_exit(),
404
			service.client(),
405
			WrappedExecutor(service.spawn_task_handle()),
406
		);
407
408
409
410
411
412
413
414
415
416
417
418
419
420

		let (validation_service_handle, validation_service) = consensus::ServiceBuilder {
			client: client.clone(),
			network: validation_network.clone(),
			collators: validation_network,
			task_executor: Arc::new(WrappedExecutor(service.spawn_task_handle())),
			availability_store: availability_store.clone(),
			select_chain: select_chain.clone(),
			keystore: service.keystore(),
			max_block_data_size,
		}.build();

		service.spawn_essential_task(Box::pin(validation_service));

421
422
423
		let proposer = consensus::ProposerFactory::new(
			client.clone(),
			service.transaction_pool(),
424
			validation_service_handle,
425
			slot_duration,
426
			backend,
427
428
429
		);

		let select_chain = service.select_chain().ok_or(ServiceError::SelectChainRequired)?;
430
431
		let can_author_with =
			consensus_common::CanAuthorWithNativeVersion::new(client.executor().clone());
432

433
434
435
		let block_import = availability_store.block_import(
			block_import,
			client.clone(),
436
			Arc::new(WrappedExecutor(service.spawn_task_handle())),
437
438
439
			service.keystore(),
		)?;

440
441
442
443
444
445
446
447
		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(),
448
			force_authoring,
449
			babe_link,
450
			can_author_with,
451
452
		};

453
		let babe = babe::start_babe(babe_config)?;
454
		service.spawn_essential_task(babe);
Gavin Wood's avatar
Gavin Wood committed
455
456

		if authority_discovery_enabled {
457
			let network = service.network();
458
459
460
			let network_event_stream = network.event_stream().compat();
			let dht_event_stream = network_event_stream.filter_map(|e| async move { match e {
				Ok(Event::Dht(e)) => Some(e),
461
				_ => None,
Gavin Wood's avatar
Gavin Wood committed
462
			}}).boxed();
Gavin Wood's avatar
Gavin Wood committed
463
464
			let authority_discovery = authority_discovery::AuthorityDiscovery::new(
				service.client(),
465
				network,
Gavin Wood's avatar
Gavin Wood committed
466
				sentry_nodes,
Gavin Wood's avatar
Gavin Wood committed
467
				service.keystore(),
Gavin Wood's avatar
Gavin Wood committed
468
				dht_event_stream,
Gavin Wood's avatar
Gavin Wood committed
469
			);
470
			service.spawn_task(authority_discovery);
Gavin Wood's avatar
Gavin Wood committed
471
		}
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
472
	}
473

Gavin Wood's avatar
Gavin Wood committed
474
475
476
	// 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 {
477
478
479
480
481
		Some(service.keystore())
	} else {
		None
	};

482
483
484
	let config = grandpa::Config {
		// FIXME substrate#1578 make this available through chainspec
		gossip_duration: Duration::from_millis(333),
485
		justification_period: 512,
Gavin Wood's avatar
Gavin Wood committed
486
		name: Some(name),
Gavin Wood's avatar
Gavin Wood committed
487
		observer_enabled: false,
488
		keystore,
Gavin Wood's avatar
Gavin Wood committed
489
		is_authority,
490
491
	};

492
493
494
495
496
497
498
499
500
	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.
		let grandpa_config = grandpa::GrandpaParams {
501
			config,
502
503
504
505
506
507
			link: link_half,
			network: service.network(),
			inherent_data_providers: inherent_data_providers.clone(),
			on_exit: service.on_exit(),
			telemetry_on_connect: Some(service.telemetry_on_connect_stream()),
			voting_rule: grandpa::VotingRulesBuilder::default().build(),
508
			executor: service.spawn_task_handle(),
509
		};
Gavin Wood's avatar
Gavin Wood committed
510

511
512
513
		service.spawn_essential_task(
			grandpa::run_grandpa_voter(grandpa_config)?.compat().map(drop)
		);
514
515
516
517
518
519
	} else {
		grandpa::setup_disabled_grandpa(
			service.client(),
			&inherent_data_providers,
			service.network(),
		)?;
520
521
522
523
524
	}

	Ok(service)
}

525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
/// Create a new Polkadot service for a light client.
pub fn polkadot_new_light(config: Configuration)
	-> Result<impl AbstractService<
		Block = Block,
		RuntimeApi = polkadot_runtime::RuntimeApi,
		NetworkSpecialization = PolkadotProtocol,
		Backend = TLightBackend<Block>,
		SelectChain = LongestChain<TLightBackend<Block>, Block>,
		CallExecutor = TLightCallExecutor<Block, PolkadotExecutor>,
	>, ServiceError>
{
	new_light(config)
}

/// Create a new Kusama service for a light client.
pub fn kusama_new_light(config: Configuration)
	-> Result<impl AbstractService<
		Block = Block,
		RuntimeApi = kusama_runtime::RuntimeApi,
		NetworkSpecialization = PolkadotProtocol,
		Backend = TLightBackend<Block>,
		SelectChain = LongestChain<TLightBackend<Block>, Block>,
		CallExecutor = TLightCallExecutor<Block, KusamaExecutor>,
	>, ServiceError>
{
	new_light(config)
}

553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
// We can't use service::TLightClient due to
// Rust bug: https://github.com/rust-lang/rust/issues/43580
type TLocalLightClient<Runtime, Dispatch> =  Client<
	sc_client::light::backend::Backend<sc_client_db::light::LightStorage<Block>, sp_core::Blake2Hasher>,
	sc_client::light::call_executor::GenesisCallExecutor<
		sc_client::light::backend::Backend<sc_client_db::light::LightStorage<Block>, sp_core::Blake2Hasher>,
		sc_client::LocalCallExecutor<
			sc_client::light::backend::Backend<
				sc_client_db::light::LightStorage<Block>,
				sp_core::Blake2Hasher
			>,
			sc_executor::NativeExecutor<Dispatch>
		>
	>,
	Block,
	Runtime
>;

571
/// Builds a new service for a light client.
572
pub fn new_light<Runtime, Dispatch, Extrinsic>(config: Configuration)
573
	-> Result<impl AbstractService<
574
575
576
577
578
579
		Block = Block,
		RuntimeApi = Runtime,
		NetworkSpecialization = PolkadotProtocol,
		Backend = TLightBackend<Block>,
		SelectChain = LongestChain<TLightBackend<Block>, Block>,
		CallExecutor = TLightCallExecutor<Block, Dispatch>,
580
	>, ServiceError>
581
where
582
583
584
585
586
	Runtime: Send + Sync + 'static,
	Runtime::RuntimeApi: RuntimeApiCollection<
		Extrinsic,
		StateBackend = sc_client_api::StateBackendFor<TLightBackend<Block>, Block>
	>,
587
588
	Dispatch: NativeExecutionDispatch + 'static,
	Extrinsic: RuntimeExtrinsic,
589
590
591
592
	Runtime: sp_api::ConstructRuntimeApi<
		Block,
		TLocalLightClient<Runtime, Dispatch>,
	>,
593
594
595
{
	let inherent_data_providers = InherentDataProviders::new();

596
	ServiceBuilder::new_light::<Block, Runtime, Dispatch>(config)?
Gavin Wood's avatar
Gavin Wood committed
597
598
		.with_select_chain(|_, backend| {
			Ok(LongestChain::new(backend.clone()))
599
		})?
Gavin Wood's avatar
Gavin Wood committed
600
601
602
		.with_transaction_pool(|config, client, fetcher| {
			let fetcher = fetcher
				.ok_or_else(|| "Trying to start light transaction pool without active fetcher")?;
603
604
605
606
			let pool_api = sc_transaction_pool::LightChainApi::new(client.clone(), fetcher.clone());
			let pool = sc_transaction_pool::BasicPool::new(config, pool_api);
			let maintainer = sc_transaction_pool::LightBasicPoolMaintainer::with_defaults(pool.pool().clone(), client, fetcher);
			let maintainable_pool = sp_transaction_pool::MaintainableTransactionPool::new(pool, maintainer);
Gavin Wood's avatar
Gavin Wood committed
607
608
			Ok(maintainable_pool)
		})?
609
		.with_import_queue_and_fprb(|_config, client, backend, fetcher, _select_chain, _| {
thiolliere's avatar
thiolliere committed
610
			let fetch_checker = fetcher
611
612
				.map(|fetcher| fetcher.checker().clone())
				.ok_or_else(|| "Trying to start light import queue without active fetch checker")?;
613
			let grandpa_block_import = grandpa::light_block_import::<_, _, _, Runtime>(
614
				client.clone(), backend, &*client, Arc::new(fetch_checker)
615
616
			)?;

617
			let finality_proof_import = grandpa_block_import.clone();
618
619
620
			let finality_proof_request_builder =
				finality_proof_import.create_finality_proof_request_builder();

621
622
623
624
625
626
627
			let (babe_block_import, babe_link) = babe::block_import(
				babe::Config::get_or_compute(&*client)?,
				grandpa_block_import,
				client.clone(),
				client.clone(),
			)?;

628
			// FIXME: pruning task isn't started since light client doesn't do `AuthoritySetup`.
629
			let import_queue = babe::import_queue(
630
631
				babe_link,
				babe_block_import,
632
633
634
635
636
637
638
639
640
641
				None,
				Some(Box::new(finality_proof_import)),
				client.clone(),
				client,
				inherent_data_providers.clone(),
			)?;

			Ok((import_queue, finality_proof_request_builder))
		})?
		.with_network_protocol(|config| Ok(PolkadotProtocol::new(config.custom.collating_for.clone())))?
Gavin Wood's avatar
Gavin Wood committed
642
643
		.with_finality_proof_provider(|client, backend|
			Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, client)) as _)
644
		)?
Gavin Wood's avatar
Gavin Wood committed
645
646
647
648
649
650
651
		.with_rpc_extensions(|client, pool, _backend, fetcher, remote_blockchain|
			-> Result<polkadot_rpc::RpcExtension, _> {
			let fetcher = fetcher
				.ok_or_else(|| "Trying to start node RPC without active fetcher")?;
			let remote_blockchain = remote_blockchain
				.ok_or_else(|| "Trying to start node RPC without active remote blockchain")?;
			Ok(polkadot_rpc::create_light(client, remote_blockchain, fetcher, pool))
652
		})?
653
		.build()
654
}