lib.rs 21.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
use sc_client::LongestChain;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
22
use std::sync::Arc;
23
use std::time::Duration;
24
use polkadot_primitives::{parachain, Hash, BlockId, AccountId, Nonce, Balance};
25
26
27
28
use polkadot_network::legacy::{
	gossip::{self as network_gossip, Known},
	validation::ValidationNetwork,
};
29
use service::{error::{Error as ServiceError}, ServiceBuilder};
30
use grandpa::{self, FinalityProofProvider as GrandpaFinalityProofProvider};
31
use inherents::InherentDataProviders;
32
use sc_executor::native_executor_instance;
33
use log::info;
34
35
36
37
pub use service::{
	AbstractService, Roles, PruningMode, TransactionPoolOptions, Error, RuntimeGenesis, ServiceBuilderCommand,
	TFullClient, TLightClient, TFullBackend, TLightBackend, TFullCallExecutor, TLightCallExecutor,
};
Gavin Wood's avatar
Gavin Wood committed
38
pub use service::config::{DatabaseConfig, full_version_from_strs};
39
pub use sc_executor::NativeExecutionDispatch;
40
41
42
43
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;
44
pub use consensus_common::SelectChain;
45
pub use polkadot_network::legacy::PolkadotProtocol;
46
pub use polkadot_primitives::parachain::{CollatorId, ParachainHost};
47
pub use polkadot_primitives::Block;
48
49
pub use sp_core::Blake2Hasher;
pub use sp_runtime::traits::{Block as BlockT, self as runtime_traits};
50
pub use sc_network::specialization::NetworkSpecialization;
51
pub use chain_spec::ChainSpec;
52
#[cfg(not(target_os = "unknown"))]
53
pub use consensus::run_validation_worker;
54
55
56
pub use codec::Codec;
pub use polkadot_runtime;
pub use kusama_runtime;
57

58
59
60
/// Configuration type that is being used.
///
/// See [`ChainSpec`] for more information why Polkadot `GenesisConfig` is safe here.
61
62
63
64
pub type Configuration = service::Configuration<
	polkadot_runtime::GenesisConfig,
	chain_spec::Extensions,
>;
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92

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,
93
	<Self as sp_api::ApiExt<Block>>::StateBackend: sp_api::StateBackend<Blake2Hasher>,
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
{}

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,
111
	<Self as sp_api::ApiExt<Block>>::StateBackend: sp_api::StateBackend<Blake2Hasher>,
112
113
114
115
116
117
118
119
120
121
122
123
124
125
{}

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

126
impl IsKusama for ChainSpec {
127
	fn is_kusama(&self) -> bool {
128
		self.name().starts_with("Kusama")
129
130
	}
}
131

132
133
134
135
136
/// 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 {
137
	($config:expr, $runtime:ty, $executor:ty) => {{
138
139
140
		let mut import_setup = None;
		let inherent_data_providers = inherents::InherentDataProviders::new();
		let builder = service::ServiceBuilder::new_full::<
141
			Block, $runtime, $executor
142
		>($config)?
Gavin Wood's avatar
Gavin Wood committed
143
			.with_select_chain(|_, backend| {
144
				Ok(sc_client::LongestChain::new(backend.clone()))
145
			})?
Gavin Wood's avatar
Gavin Wood committed
146
			.with_transaction_pool(|config, client, _fetcher| {
147
				let pool_api = sc_transaction_pool::FullChainApi::new(client.clone());
148
				let pool = sc_transaction_pool::BasicPool::new(config, std::sync::Arc::new(pool_api));
Gavin Wood's avatar
Gavin Wood committed
149
				Ok(pool)
Gavin Wood's avatar
Gavin Wood committed
150
			})?
151
			.with_import_queue(|_config, client, mut select_chain, _| {
152
153
				let select_chain = select_chain.take()
					.ok_or_else(|| service::Error::SelectChainRequired)?;
154
				let (grandpa_block_import, grandpa_link) =
155
					grandpa::block_import::<_, _, _, Runtime, _>(
156
						client.clone(), &*client, select_chain
thiolliere's avatar
thiolliere committed
157
					)?;
158
159
160
				let justification_import = grandpa_block_import.clone();

				let (block_import, babe_link) = babe::block_import(
161
162
163
164
					babe::Config::get_or_compute(&*client)?,
					grandpa_block_import,
					client.clone(),
					client.clone(),
165
166
				)?;

167
				let import_queue = babe::import_queue(
168
169
170
171
172
173
174
					babe_link.clone(),
					block_import.clone(),
					Some(Box::new(justification_import)),
					None,
					client.clone(),
					client,
					inherent_data_providers.clone(),
175
				)?;
176

177
				import_setup = Some((block_import, grandpa_link, babe_link));
178
				Ok(import_queue)
179
			})?
180
181
			.with_rpc_extensions(|builder| -> Result<polkadot_rpc::RpcExtension, _> {
				Ok(polkadot_rpc::create_full(builder.client().clone(), builder.pool()))
182
			})?;
183

184
		(builder, import_setup, inherent_data_providers)
185
186
	}}
}
187

188
/// Builds a new object suitable for chain operations.
189
pub fn new_chain_ops<Runtime, Dispatch, Extrinsic>(mut config: Configuration)
190
	-> Result<impl ServiceBuilderCommand<Block=Block>, ServiceError>
191
192
where
	Runtime: ConstructRuntimeApi<Block, service::TFullClient<Block, Runtime, Dispatch>> + Send + Sync + 'static,
193
	Runtime::RuntimeApi:
194
	RuntimeApiCollection<Extrinsic, StateBackend = sc_client_api::StateBackendFor<TFullBackend<Block>, Block>>,
195
196
	Dispatch: NativeExecutionDispatch + 'static,
	Extrinsic: RuntimeExtrinsic,
197
	<Runtime::RuntimeApi as sp_api::ApiExt<Block>>::StateBackend: sp_api::StateBackend<Blake2Hasher>,
198
{
199
	config.keystore = service::config::KeystoreConfig::InMemory;
200
201
202
203
	Ok(new_full_start!(config, Runtime, Dispatch).0)
}

/// Create a new Polkadot service for a full node.
Gavin Wood's avatar
Gavin Wood committed
204
205
206
207
208
209
210
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,
)
211
212
213
214
215
216
217
218
219
	-> Result<impl AbstractService<
		Block = Block,
		RuntimeApi = polkadot_runtime::RuntimeApi,
		NetworkSpecialization = PolkadotProtocol,
		Backend = TFullBackend<Block>,
		SelectChain = LongestChain<TFullBackend<Block>, Block>,
		CallExecutor = TFullCallExecutor<Block, PolkadotExecutor>,
	>, ServiceError>
{
Gavin Wood's avatar
Gavin Wood committed
220
	new_full(config, collating_for, max_block_data_size, authority_discovery_enabled, slot_duration)
221
222
223
}

/// Create a new Kusama service for a full node.
Gavin Wood's avatar
Gavin Wood committed
224
225
226
227
228
229
230
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,
)
231
232
233
234
235
236
237
238
239
	-> Result<impl AbstractService<
		Block = Block,
		RuntimeApi = kusama_runtime::RuntimeApi,
		NetworkSpecialization = PolkadotProtocol,
		Backend = TFullBackend<Block>,
		SelectChain = LongestChain<TFullBackend<Block>, Block>,
		CallExecutor = TFullCallExecutor<Block, KusamaExecutor>,
	>, ServiceError>
{
Gavin Wood's avatar
Gavin Wood committed
240
	new_full(config, collating_for, max_block_data_size, authority_discovery_enabled, slot_duration)
241
}
242

243
/// Builds a new service for a full client.
Gavin Wood's avatar
Gavin Wood committed
244
245
246
247
248
249
250
pub fn new_full<Runtime, Dispatch, Extrinsic>(
	config: Configuration,
	collating_for: Option<(CollatorId, parachain::Id)>,
	max_block_data_size: Option<u64>,
	authority_discovery_enabled: bool,
	slot_duration: u64,
)
251
	-> Result<impl AbstractService<
252
253
254
255
256
257
		Block = Block,
		RuntimeApi = Runtime,
		NetworkSpecialization = PolkadotProtocol,
		Backend = TFullBackend<Block>,
		SelectChain = LongestChain<TFullBackend<Block>, Block>,
		CallExecutor = TFullCallExecutor<Block, Dispatch>,
258
	>, ServiceError>
259
260
	where
		Runtime: ConstructRuntimeApi<Block, service::TFullClient<Block, Runtime, Dispatch>> + Send + Sync + 'static,
261
262
		Runtime::RuntimeApi:
			RuntimeApiCollection<Extrinsic, StateBackend = sc_client_api::StateBackendFor<TFullBackend<Block>, Block>>,
263
264
		Dispatch: NativeExecutionDispatch + 'static,
		Extrinsic: RuntimeExtrinsic,
265
266
		// Rust bug: https://github.com/rust-lang/rust/issues/24159
		<Runtime::RuntimeApi as sp_api::ApiExt<Block>>::StateBackend: sp_api::StateBackend<Blake2Hasher>,
267
{
268
	use sc_network::Event;
Gavin Wood's avatar
Gavin Wood committed
269
	use futures::stream::StreamExt;
270

Gavin Wood's avatar
Gavin Wood committed
271
	let is_collator = collating_for.is_some();
272
	let is_authority = config.roles.is_authority() && !is_collator;
Gavin Wood's avatar
Gavin Wood committed
273
	let force_authoring = config.force_authoring;
Gavin Wood's avatar
Gavin Wood committed
274
	let max_block_data_size = max_block_data_size;
Gavin Wood's avatar
Gavin Wood committed
275
	let db_path = if let Some(DatabaseConfig::Path { ref path, .. }) = config.database {
Gavin Wood's avatar
Gavin Wood committed
276
277
278
279
		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
280
281
	let disable_grandpa = config.disable_grandpa;
	let name = config.name.clone();
Gavin Wood's avatar
Gavin Wood committed
282
	let authority_discovery_enabled = authority_discovery_enabled;
Gavin Wood's avatar
Gavin Wood committed
283
	let sentry_nodes = config.network.sentry_nodes.clone();
Gavin Wood's avatar
Gavin Wood committed
284
	let slot_duration = slot_duration;
Gavin Wood's avatar
Gavin Wood committed
285

Gavin Wood's avatar
Gavin Wood committed
286
287
288
289
290
	// 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;

291
	let (builder, mut import_setup, inherent_data_providers) = new_full_start!(config, Runtime, Dispatch);
292

293
294
	let backend = builder.backend().clone();

295
	let service = builder
Gavin Wood's avatar
Gavin Wood committed
296
		.with_network_protocol(|_config| Ok(PolkadotProtocol::new(collating_for.clone())))?
Gavin Wood's avatar
Gavin Wood committed
297
298
		.with_finality_proof_provider(|client, backend|
			Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, client)) as _)
299
300
301
		)?
		.build()?;

André Silva's avatar
André Silva committed
302
	let (block_import, link_half, babe_link) = import_setup.take()
303
304
305
306
307
308
309
310
311
312
313
		.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();
314
315

	let is_known = move |block_hash: &Hash| {
316
		use consensus_common::BlockStatus;
317
318
319
320
321
322
323
324
325
326
327
328

		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)
					},
329
				}
thiolliere's avatar
thiolliere committed
330
			}
331
332
333
		}
	};

334
	let mut gossip_validator = network_gossip::register_validator(
335
336
		service.network(),
		(is_known, client.clone()),
337
		&service.spawn_task_handle(),
338
339
	);

Gavin Wood's avatar
Gavin Wood committed
340
	if participates_in_consensus {
341
		let availability_store = {
342
343
			use std::path::PathBuf;

Gavin Wood's avatar
Gavin Wood committed
344
			let mut path = PathBuf::from(db_path);
345
346
			path.push("availability");

347
348
			let gossip = polkadot_network::legacy
				::AvailabilityNetworkShim(gossip_validator.clone());
349
350
351
352
353
354
355
356
357
358
359

			#[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)
360
361
		};

362
363
364
365
366
367
368
		{
			let availability_store = availability_store.clone();
			service.network().with_spec(
				|spec, _ctx| spec.register_availability_store(availability_store)
			);
		}

369
370
371
372
373
		{
			let availability_store = availability_store.clone();
			gossip_validator.register_availability_store(availability_store);
		}

374
375
376
377
		// collator connections and validation network both fulfilled by this
		let validation_network = ValidationNetwork::new(
			gossip_validator,
			service.client(),
378
			service.spawn_task_handle(),
379
		);
380
381
382
383
384

		let (validation_service_handle, validation_service) = consensus::ServiceBuilder {
			client: client.clone(),
			network: validation_network.clone(),
			collators: validation_network,
385
			spawner: service.spawn_task_handle(),
386
387
388
389
390
391
			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
392
		service.spawn_essential_task("validation-service", Box::pin(validation_service));
393

394
395
396
		let proposer = consensus::ProposerFactory::new(
			client.clone(),
			service.transaction_pool(),
397
			validation_service_handle,
398
			slot_duration,
399
			backend,
400
401
402
		);

		let select_chain = service.select_chain().ok_or(ServiceError::SelectChainRequired)?;
403
404
		let can_author_with =
			consensus_common::CanAuthorWithNativeVersion::new(client.executor().clone());
405

406
407
408
		let block_import = availability_store.block_import(
			block_import,
			client.clone(),
409
			service.spawn_task_handle(),
410
411
412
			service.keystore(),
		)?;

413
414
415
416
417
418
419
420
		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(),
421
			force_authoring,
422
			babe_link,
423
			can_author_with,
424
425
		};

426
		let babe = babe::start_babe(babe_config)?;
Gavin Wood's avatar
Gavin Wood committed
427
		service.spawn_essential_task("babe", babe);
Gavin Wood's avatar
Gavin Wood committed
428
429

		if authority_discovery_enabled {
430
			let network = service.network();
431
			let network_event_stream = network.event_stream();
432
			let dht_event_stream = network_event_stream.filter_map(|e| async move { match e {
433
				Event::Dht(e) => Some(e),
434
				_ => None,
Gavin Wood's avatar
Gavin Wood committed
435
			}}).boxed();
Gavin Wood's avatar
Gavin Wood committed
436
437
			let authority_discovery = authority_discovery::AuthorityDiscovery::new(
				service.client(),
438
				network,
Gavin Wood's avatar
Gavin Wood committed
439
				sentry_nodes,
Gavin Wood's avatar
Gavin Wood committed
440
				service.keystore(),
Gavin Wood's avatar
Gavin Wood committed
441
				dht_event_stream,
Gavin Wood's avatar
Gavin Wood committed
442
			);
Gavin Wood's avatar
Gavin Wood committed
443
			service.spawn_task("authority-discovery", authority_discovery);
Gavin Wood's avatar
Gavin Wood committed
444
		}
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
445
	}
446

Gavin Wood's avatar
Gavin Wood committed
447
448
449
	// 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 {
450
451
452
453
454
		Some(service.keystore())
	} else {
		None
	};

455
456
	let config = grandpa::Config {
		// FIXME substrate#1578 make this available through chainspec
457
		gossip_duration: Duration::from_millis(1000),
458
		justification_period: 512,
Gavin Wood's avatar
Gavin Wood committed
459
		name: Some(name),
Gavin Wood's avatar
Gavin Wood committed
460
		observer_enabled: false,
461
		keystore,
Gavin Wood's avatar
Gavin Wood committed
462
		is_authority,
463
464
	};

465
466
467
468
469
470
471
472
473
	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 {
474
			config,
475
476
477
478
479
480
481
			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(),
		};
Gavin Wood's avatar
Gavin Wood committed
482

483
		service.spawn_essential_task(
Gavin Wood's avatar
Gavin Wood committed
484
485
			"grandpa-voter",
			grandpa::run_grandpa_voter(grandpa_config)?
486
		);
487
488
489
490
491
492
	} else {
		grandpa::setup_disabled_grandpa(
			service.client(),
			&inherent_data_providers,
			service.network(),
		)?;
493
494
495
496
497
	}

	Ok(service)
}

498
/// Create a new Polkadot service for a light client.
Gavin Wood's avatar
Gavin Wood committed
499
500
501
502
pub fn polkadot_new_light(
	config: Configuration,
	collating_for: Option<(CollatorId, parachain::Id)>,
)
503
504
505
506
507
508
509
510
511
	-> Result<impl AbstractService<
		Block = Block,
		RuntimeApi = polkadot_runtime::RuntimeApi,
		NetworkSpecialization = PolkadotProtocol,
		Backend = TLightBackend<Block>,
		SelectChain = LongestChain<TLightBackend<Block>, Block>,
		CallExecutor = TLightCallExecutor<Block, PolkadotExecutor>,
	>, ServiceError>
{
Gavin Wood's avatar
Gavin Wood committed
512
	new_light(config, collating_for)
513
514
515
}

/// Create a new Kusama service for a light client.
Gavin Wood's avatar
Gavin Wood committed
516
517
518
519
pub fn kusama_new_light(
	config: Configuration,
	collating_for: Option<(CollatorId, parachain::Id)>,
)
520
521
522
523
524
525
526
527
528
	-> Result<impl AbstractService<
		Block = Block,
		RuntimeApi = kusama_runtime::RuntimeApi,
		NetworkSpecialization = PolkadotProtocol,
		Backend = TLightBackend<Block>,
		SelectChain = LongestChain<TLightBackend<Block>, Block>,
		CallExecutor = TLightCallExecutor<Block, KusamaExecutor>,
	>, ServiceError>
{
Gavin Wood's avatar
Gavin Wood committed
529
	new_light(config, collating_for)
530
531
}

532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
// 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
>;

550
/// Builds a new service for a light client.
Gavin Wood's avatar
Gavin Wood committed
551
552
553
554
pub fn new_light<Runtime, Dispatch, Extrinsic>(
	config: Configuration,
	collating_for: Option<(CollatorId, parachain::Id)>,
)
555
	-> Result<impl AbstractService<
556
557
558
559
560
561
		Block = Block,
		RuntimeApi = Runtime,
		NetworkSpecialization = PolkadotProtocol,
		Backend = TLightBackend<Block>,
		SelectChain = LongestChain<TLightBackend<Block>, Block>,
		CallExecutor = TLightCallExecutor<Block, Dispatch>,
562
	>, ServiceError>
563
where
564
565
566
567
568
	Runtime: Send + Sync + 'static,
	Runtime::RuntimeApi: RuntimeApiCollection<
		Extrinsic,
		StateBackend = sc_client_api::StateBackendFor<TLightBackend<Block>, Block>
	>,
569
570
	Dispatch: NativeExecutionDispatch + 'static,
	Extrinsic: RuntimeExtrinsic,
571
572
573
574
	Runtime: sp_api::ConstructRuntimeApi<
		Block,
		TLocalLightClient<Runtime, Dispatch>,
	>,
575
576
577
{
	let inherent_data_providers = InherentDataProviders::new();

578
	ServiceBuilder::new_light::<Block, Runtime, Dispatch>(config)?
Gavin Wood's avatar
Gavin Wood committed
579
580
		.with_select_chain(|_, backend| {
			Ok(LongestChain::new(backend.clone()))
581
		})?
Gavin Wood's avatar
Gavin Wood committed
582
583
584
		.with_transaction_pool(|config, client, fetcher| {
			let fetcher = fetcher
				.ok_or_else(|| "Trying to start light transaction pool without active fetcher")?;
585
			let pool_api = sc_transaction_pool::LightChainApi::new(client.clone(), fetcher.clone());
Gavin Wood's avatar
Gavin Wood committed
586
			let pool = sc_transaction_pool::BasicPool::with_revalidation_type(
587
				config, Arc::new(pool_api), sc_transaction_pool::RevalidationType::Light,
Gavin Wood's avatar
Gavin Wood committed
588
589
			);
			Ok(pool)
Gavin Wood's avatar
Gavin Wood committed
590
		})?
591
		.with_import_queue_and_fprb(|_config, client, backend, fetcher, _select_chain, _| {
thiolliere's avatar
thiolliere committed
592
			let fetch_checker = fetcher
593
594
				.map(|fetcher| fetcher.checker().clone())
				.ok_or_else(|| "Trying to start light import queue without active fetch checker")?;
595
			let grandpa_block_import = grandpa::light_block_import::<_, _, _, Runtime>(
596
				client.clone(), backend, &*client, Arc::new(fetch_checker)
597
598
			)?;

599
			let finality_proof_import = grandpa_block_import.clone();
600
601
602
			let finality_proof_request_builder =
				finality_proof_import.create_finality_proof_request_builder();

603
604
605
606
607
608
609
			let (babe_block_import, babe_link) = babe::block_import(
				babe::Config::get_or_compute(&*client)?,
				grandpa_block_import,
				client.clone(),
				client.clone(),
			)?;

610
			// FIXME: pruning task isn't started since light client doesn't do `AuthoritySetup`.
611
			let import_queue = babe::import_queue(
612
613
				babe_link,
				babe_block_import,
614
615
616
617
618
619
620
621
622
				None,
				Some(Box::new(finality_proof_import)),
				client.clone(),
				client,
				inherent_data_providers.clone(),
			)?;

			Ok((import_queue, finality_proof_request_builder))
		})?
Gavin Wood's avatar
Gavin Wood committed
623
		.with_network_protocol(|_config| Ok(PolkadotProtocol::new(collating_for.clone())))?
Gavin Wood's avatar
Gavin Wood committed
624
625
		.with_finality_proof_provider(|client, backend|
			Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, client)) as _)
626
		)?
627
		.with_rpc_extensions(|builder|
Gavin Wood's avatar
Gavin Wood committed
628
			-> Result<polkadot_rpc::RpcExtension, _> {
629
			let fetcher = builder.fetcher()
Gavin Wood's avatar
Gavin Wood committed
630
				.ok_or_else(|| "Trying to start node RPC without active fetcher")?;
631
			let remote_blockchain = builder.remote_backend()
Gavin Wood's avatar
Gavin Wood committed
632
				.ok_or_else(|| "Trying to start node RPC without active remote blockchain")?;
633
634

			Ok(polkadot_rpc::create_light(builder.client().clone(), remote_blockchain, fetcher, builder.pool()))
635
		})?
636
		.build()
637
}