lib.rs 37.1 KB
Newer Older
1
// Copyright 2017-2021 Parity Technologies (UK) Ltd.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 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/>.

//! Polkadot service. Specialized wrapper over substrate service.

19
20
#![deny(unused_results)]

21
pub mod chain_spec;
22
mod grandpa_support;
23
mod parachains_db;
24
mod relay_chain_selection;
25

26
pub mod overseer;
27

28
pub use self::overseer::{OverseerGen, OverseerGenArgs, RealOverseerGen};
29

30
#[cfg(all(test, feature = "disputes"))]
31
32
mod tests;

Squirrel's avatar
Squirrel committed
33
34
35
36
37
38
use grandpa::{self, FinalityProofProvider as GrandpaFinalityProofProvider};
use polkadot_node_core_approval_voting::Config as ApprovalVotingConfig;
use polkadot_node_core_av_store::{Config as AvailabilityConfig, Error as AvailabilityError};
use polkadot_node_core_candidate_validation::Config as CandidateValidationConfig;
use polkadot_node_core_chain_selection::{
	self as chain_selection_subsystem, Config as ChainSelectionConfig,
39
};
Squirrel's avatar
Squirrel committed
40
41
42
43
44
use polkadot_node_core_dispute_coordinator::Config as DisputeCoordinatorConfig;
use polkadot_overseer::BlockInfo;
use sc_client_api::ExecutorProvider;
use sp_trie::PrefixedMemoryDB;
use tracing::info;
45

Shawn Tabrizi's avatar
Shawn Tabrizi committed
46
pub use sp_core::traits::SpawnNamed;
Squirrel's avatar
Squirrel committed
47

Squirrel's avatar
Squirrel committed
48
49
50
51
52
53
54
pub use polkadot_overseer::{Handle, Overseer, OverseerConnector, OverseerHandle};
pub use polkadot_primitives::v1::ParachainHost;
pub use relay_chain_selection::SelectRelayChain;
pub use sc_client_api::AuxStore;
pub use sp_authority_discovery::AuthorityDiscoveryApi;
pub use sp_blockchain::HeaderBackend;
pub use sp_consensus_babe::BabeApi;
55
56
57

use polkadot_subsystem::jaeger;

Shawn Tabrizi's avatar
Shawn Tabrizi committed
58
use std::{sync::Arc, time::Duration};
59

60
use prometheus_endpoint::Registry;
Squirrel's avatar
Squirrel committed
61
62
use service::{KeystoreContainer, RpcHandlers};
use telemetry::{Telemetry, TelemetryWorker, TelemetryWorkerHandle};
63

64
#[cfg(feature = "rococo-native")]
65
pub use polkadot_client::RococoExecutorDispatch;
66
67

#[cfg(feature = "westend-native")]
68
pub use polkadot_client::WestendExecutorDispatch;
69
70

#[cfg(feature = "kusama-native")]
71
pub use polkadot_client::KusamaExecutorDispatch;
72

73
74
75
#[cfg(feature = "polkadot-native")]
pub use polkadot_client::PolkadotExecutorDispatch;

Shawn Tabrizi's avatar
Shawn Tabrizi committed
76
77
pub use chain_spec::{KusamaChainSpec, PolkadotChainSpec, RococoChainSpec, WestendChainSpec};
pub use consensus_common::{block_validation::Chain, Proposal, SelectChain};
78
pub use polkadot_client::{
Shawn Tabrizi's avatar
Shawn Tabrizi committed
79
	AbstractClient, Client, ClientHandle, ExecuteWithClient, FullBackend, FullClient,
80
	RuntimeApiCollection,
81
};
82
pub use polkadot_primitives::v1::{Block, BlockId, CollatorPair, Hash, Id as ParaId};
Shawn Tabrizi's avatar
Shawn Tabrizi committed
83
pub use sc_client_api::{Backend, CallExecutor, ExecutionStrategy};
84
pub use sc_consensus::{BlockImport, LongestChain};
85
use sc_executor::NativeElseWasmExecutor;
86
pub use sc_executor::NativeExecutionDispatch;
87
pub use service::{
88
	config::{DatabaseSource, PrometheusConfig},
Shawn Tabrizi's avatar
Shawn Tabrizi committed
89
	ChainSpec, Configuration, Error as SubstrateServiceError, PruningMode, Role, RuntimeGenesis,
Squirrel's avatar
Squirrel committed
90
	TFullBackend, TFullCallExecutor, TFullClient, TaskManager, TransactionPoolOptions,
91
};
Shawn Tabrizi's avatar
Shawn Tabrizi committed
92
pub use sp_api::{ApiRef, ConstructRuntimeApi, Core as CoreApi, ProvideRuntimeApi, StateBackend};
93
94
95
pub use sp_runtime::{
	generic,
	traits::{
Shawn Tabrizi's avatar
Shawn Tabrizi committed
96
97
		self as runtime_traits, BlakeTwo256, Block as BlockT, DigestFor, HashFor,
		Header as HeaderT, NumberFor,
98
99
	},
};
100

101
#[cfg(feature = "kusama-native")]
102
pub use kusama_runtime;
103
#[cfg(feature = "polkadot-native")]
104
pub use polkadot_runtime;
105
#[cfg(feature = "rococo-native")]
106
pub use rococo_runtime;
107
#[cfg(feature = "westend-native")]
108
109
pub use westend_runtime;

110
111
112
/// The maximum number of active leaves we forward to the [`Overseer`] on startup.
const MAX_ACTIVE_LEAVES: usize = 4;

113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
/// Provides the header and block number for a hash.
///
/// Decouples `sc_client_api::Backend` and `sp_blockchain::HeaderBackend`.
pub trait HeaderProvider<Block, Error = sp_blockchain::Error>: Send + Sync + 'static
where
	Block: BlockT,
	Error: std::fmt::Debug + Send + Sync + 'static,
{
	/// Obtain the header for a hash.
	fn header(
		&self,
		hash: <Block as BlockT>::Hash,
	) -> Result<Option<<Block as BlockT>::Header>, Error>;
	/// Obtain the block number for a hash.
	fn number(
		&self,
		hash: <Block as BlockT>::Hash,
	) -> Result<Option<<<Block as BlockT>::Header as HeaderT>::Number>, Error>;
}

impl<Block, T> HeaderProvider<Block> for T
where
	Block: BlockT,
	T: sp_blockchain::HeaderBackend<Block> + 'static,
{
	fn header(
		&self,
		hash: Block::Hash,
	) -> sp_blockchain::Result<Option<<Block as BlockT>::Header>> {
		<Self as sp_blockchain::HeaderBackend<Block>>::header(
			self,
			generic::BlockId::<Block>::Hash(hash),
		)
	}
	fn number(
		&self,
		hash: Block::Hash,
	) -> sp_blockchain::Result<Option<<<Block as BlockT>::Header as HeaderT>::Number>> {
		<Self as sp_blockchain::HeaderBackend<Block>>::number(self, hash)
	}
}

/// Decoupling the provider.
///
/// Mandated since `trait HeaderProvider` can only be
/// implemented once for a generic `T`.
pub trait HeaderProviderProvider<Block>: Send + Sync + 'static
where
	Block: BlockT,
{
	type Provider: HeaderProvider<Block> + 'static;

	fn header_provider(&self) -> &Self::Provider;
}

impl<Block, T> HeaderProviderProvider<Block> for T
where
	Block: BlockT,
	T: sc_client_api::Backend<Block> + 'static,
{
	type Provider = <T as sc_client_api::Backend<Block>>::Blockchain;

	fn header_provider(&self) -> &Self::Provider {
		self.blockchain()
	}
}

180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#[derive(thiserror::Error, Debug)]
pub enum Error {
	#[error(transparent)]
	Io(#[from] std::io::Error),

	#[error(transparent)]
	AddrFormatInvalid(#[from] std::net::AddrParseError),

	#[error(transparent)]
	Sub(#[from] SubstrateServiceError),

	#[error(transparent)]
	Blockchain(#[from] sp_blockchain::Error),

	#[error(transparent)]
	Consensus(#[from] consensus_common::Error),

	#[error("Failed to create an overseer")]
	Overseer(#[from] polkadot_overseer::SubsystemError),

	#[error(transparent)]
	Prometheus(#[from] prometheus_endpoint::PrometheusError),

203
204
205
	#[error(transparent)]
	Telemetry(#[from] telemetry::Error),

206
207
208
	#[error(transparent)]
	Jaeger(#[from] polkadot_subsystem::jaeger::JaegerError),

209
210
211
212
213
	#[error(transparent)]
	Availability(#[from] AvailabilityError),

	#[error("Authorities require the real overseer implementation")]
	AuthoritiesRequireRealOverseer,
214
215
216

	#[error("Creating a custom database is required for validators")]
	DatabasePathRequired,
217
218
219

	#[error("Expected at least one of polkadot, kusama, westend or rococo runtime feature")]
	NoRuntime,
220
221
}

222
/// Can be called for a `Configuration` to identify which network the configuration targets.
223
224
225
226
227
228
pub trait IdentifyVariant {
	/// Returns if this is a configuration for the `Kusama` network.
	fn is_kusama(&self) -> bool;

	/// Returns if this is a configuration for the `Westend` network.
	fn is_westend(&self) -> bool;
229
230
231

	/// Returns if this is a configuration for the `Rococo` network.
	fn is_rococo(&self) -> bool;
232

233
234
235
	/// Returns if this is a configuration for the `Wococo` test network.
	fn is_wococo(&self) -> bool;

236
237
	/// Returns true if this configuration is for a development network.
	fn is_dev(&self) -> bool;
238
239
240
241
242
243
244
245
246
}

impl IdentifyVariant for Box<dyn ChainSpec> {
	fn is_kusama(&self) -> bool {
		self.id().starts_with("kusama") || self.id().starts_with("ksm")
	}
	fn is_westend(&self) -> bool {
		self.id().starts_with("westend") || self.id().starts_with("wnd")
	}
247
248
249
	fn is_rococo(&self) -> bool {
		self.id().starts_with("rococo") || self.id().starts_with("rco")
	}
250
251
252
	fn is_wococo(&self) -> bool {
		self.id().starts_with("wococo") || self.id().starts_with("wco")
	}
253
254
255
	fn is_dev(&self) -> bool {
		self.id().ends_with("dev")
	}
256
257
258
}

// If we're using prometheus, use a registry with a prefix of `polkadot`.
259
fn set_prometheus_registry(config: &mut Configuration) -> Result<(), Error> {
260
261
262
263
264
265
266
	if let Some(PrometheusConfig { registry, .. }) = config.prometheus_config.as_mut() {
		*registry = Registry::new_custom(Some("polkadot".into()), None)?;
	}

	Ok(())
}

267
268
/// Initialize the `Jeager` collector. The destination must listen
/// on the given address and port for `UDP` packets.
269
270
271
272
273
fn jaeger_launch_collector_with_agent(
	spawner: impl SpawnNamed,
	config: &Configuration,
	agent: Option<std::net::SocketAddr>,
) -> Result<(), Error> {
274
275
276
277
278
279
280
281
282
283
284
	if let Some(agent) = agent {
		let cfg = jaeger::JaegerConfig::builder()
			.agent(agent)
			.named(&config.network.node_name)
			.build();

		jaeger::Jaeger::new(cfg).launch(spawner)?;
	}
	Ok(())
}

285
type FullSelectChain = relay_chain_selection::SelectRelayChain<FullBackend>;
Squirrel's avatar
Squirrel committed
286

287
288
289
290
291
292
293
type FullGrandpaBlockImport<RuntimeApi, ExecutorDispatch, ChainSelection = FullSelectChain> =
	grandpa::GrandpaBlockImport<
		FullBackend,
		Block,
		FullClient<RuntimeApi, ExecutorDispatch>,
		ChainSelection,
	>;
294

295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
struct Basics<RuntimeApi, ExecutorDispatch>
where
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>
		+ Send
		+ Sync
		+ 'static,
	RuntimeApi::RuntimeApi:
		RuntimeApiCollection<StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,
	ExecutorDispatch: NativeExecutionDispatch + 'static,
{
	task_manager: TaskManager,
	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
	backend: Arc<FullBackend>,
	keystore_container: KeystoreContainer,
	telemetry: Option<Telemetry>,
}

fn new_partial_basics<RuntimeApi, ExecutorDispatch>(
313
314
315
	config: &mut Configuration,
	jaeger_agent: Option<std::net::SocketAddr>,
	telemetry_worker_handle: Option<TelemetryWorkerHandle>,
316
) -> Result<Basics<RuntimeApi, ExecutorDispatch>, Error>
Shawn Tabrizi's avatar
Shawn Tabrizi committed
317
where
318
319
320
321
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>
		+ Send
		+ Sync
		+ 'static,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
322
	RuntimeApi::RuntimeApi:
323
		RuntimeApiCollection<StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,
324
	ExecutorDispatch: NativeExecutionDispatch + 'static,
325
{
326
	set_prometheus_registry(config)?;
327

Shawn Tabrizi's avatar
Shawn Tabrizi committed
328
329
330
	let telemetry = config
		.telemetry_endpoints
		.clone()
331
332
333
334
335
336
337
338
339
340
341
342
343
344
		.filter(|x| !x.is_empty())
		.map(move |endpoints| -> Result<_, telemetry::Error> {
			let (worker, mut worker_handle) = if let Some(worker_handle) = telemetry_worker_handle {
				(None, worker_handle)
			} else {
				let worker = TelemetryWorker::new(16)?;
				let worker_handle = worker.handle();
				(Some(worker), worker_handle)
			};
			let telemetry = worker_handle.new_telemetry(endpoints);
			Ok((worker, telemetry))
		})
		.transpose()?;

345
346
347
348
349
350
	let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(
		config.wasm_method,
		config.default_heap_pages,
		config.max_runtime_instances,
	);

351
	let (client, backend, keystore_container, task_manager) =
352
		service::new_full_parts::<Block, RuntimeApi, _>(
353
354
			&config,
			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
355
			executor,
356
		)?;
357
358
	let client = Arc::new(client);

359
	let telemetry = telemetry.map(|(worker, telemetry)| {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
360
361
362
363
364
		if let Some(worker) = worker {
			task_manager.spawn_handle().spawn("telemetry", worker.run());
		}
		telemetry
	});
365

366
367
	jaeger_launch_collector_with_agent(task_manager.spawn_handle(), &*config, jaeger_agent)?;

368
369
	Ok(Basics { task_manager, client, backend, keystore_container, telemetry })
}
370

371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
fn new_partial<RuntimeApi, ExecutorDispatch, ChainSelection>(
	config: &mut Configuration,
	Basics { task_manager, backend, client, keystore_container, telemetry }: Basics<
		RuntimeApi,
		ExecutorDispatch,
	>,
	select_chain: ChainSelection,
) -> Result<
	service::PartialComponents<
		FullClient<RuntimeApi, ExecutorDispatch>,
		FullBackend,
		ChainSelection,
		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
		(
			impl service::RpcExtensionBuilder,
			(
				babe::BabeBlockImport<
					Block,
					FullClient<RuntimeApi, ExecutorDispatch>,
					FullGrandpaBlockImport<RuntimeApi, ExecutorDispatch, ChainSelection>,
				>,
				grandpa::LinkHalf<Block, FullClient<RuntimeApi, ExecutorDispatch>, ChainSelection>,
				babe::BabeLink<Block>,
				beefy_gadget::notification::BeefySignedCommitmentSender<Block>,
			),
			grandpa::SharedVoterState,
			std::time::Duration, // slot-duration
			Option<Telemetry>,
		),
	>,
	Error,
>
where
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>
		+ Send
		+ Sync
		+ 'static,
	RuntimeApi::RuntimeApi:
		RuntimeApiCollection<StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,
	ExecutorDispatch: NativeExecutionDispatch + 'static,
	ChainSelection: 'static + SelectChain<Block>,
{
414
415
	let transaction_pool = sc_transaction_pool::BasicPool::new_full(
		config.transaction_pool.clone(),
416
		config.role.is_authority().into(),
417
		config.prometheus_registry(),
418
		task_manager.spawn_essential_handle(),
419
420
421
422
423
424
425
426
427
		client.clone(),
	);

	let grandpa_hard_forks = if config.chain_spec.is_kusama() {
		grandpa_support::kusama_hard_forks()
	} else {
		Vec::new()
	};

Shawn Tabrizi's avatar
Shawn Tabrizi committed
428
429
430
431
432
433
434
	let (grandpa_block_import, grandpa_link) = grandpa::block_import_with_authority_set_hard_forks(
		client.clone(),
		&(client.clone() as Arc<_>),
		select_chain.clone(),
		grandpa_hard_forks,
		telemetry.as_ref().map(|x| x.handle()),
	)?;
435
436
437

	let justification_import = grandpa_block_import.clone();

438
	let babe_config = babe::Config::get_or_compute(&*client)?;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
439
440
	let (block_import, babe_link) =
		babe::block_import(babe_config.clone(), grandpa_block_import, client.clone())?;
441

442
	let slot_duration = babe_link.config().slot_duration();
443
444
445
446
447
448
	let import_queue = babe::import_queue(
		babe_link.clone(),
		block_import.clone(),
		Some(Box::new(justification_import)),
		client.clone(),
		select_chain.clone(),
449
450
451
452
453
454
455
456
457
458
459
		move |_, ()| async move {
			let timestamp = sp_timestamp::InherentDataProvider::from_system_time();

			let slot =
				sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_duration(
					*timestamp,
					slot_duration,
				);

			Ok((timestamp, slot))
		},
460
		&task_manager.spawn_essential_handle(),
461
		config.prometheus_registry(),
Wei Tang's avatar
Wei Tang committed
462
		consensus_common::CanAuthorWithNativeVersion::new(client.executor().clone()),
463
		telemetry.as_ref().map(|x| x.handle()),
464
465
	)?;

466
467
468
	let (beefy_link, beefy_commitment_stream) =
		beefy_gadget::notification::BeefySignedCommitmentStream::channel();

469
	let justification_stream = grandpa_link.justification_stream();
470
471
	let shared_authority_set = grandpa_link.shared_authority_set().clone();
	let shared_voter_state = grandpa::SharedVoterState::empty();
472
473
474
475
	let finality_proof_provider = GrandpaFinalityProofProvider::new_for_service(
		backend.clone(),
		Some(shared_authority_set.clone()),
	);
476

477
	let import_setup = (block_import.clone(), grandpa_link, babe_link.clone(), beefy_link);
478
	let rpc_setup = shared_voter_state.clone();
479
480

	let shared_epoch_changes = babe_link.epoch_changes().clone();
481
	let slot_duration = babe_config.slot_duration();
482
483
484

	let rpc_extensions_builder = {
		let client = client.clone();
485
		let keystore = keystore_container.sync_keystore();
486
487
		let transaction_pool = transaction_pool.clone();
		let select_chain = select_chain.clone();
488
		let chain_spec = config.chain_spec.cloned_box();
489

Shawn Tabrizi's avatar
Shawn Tabrizi committed
490
491
		move |deny_unsafe,
		      subscription_executor: polkadot_rpc::SubscriptionTaskExecutor|
492
		      -> Result<polkadot_rpc::RpcExtension, service::Error> {
493
494
495
496
			let deps = polkadot_rpc::FullDeps {
				client: client.clone(),
				pool: transaction_pool.clone(),
				select_chain: select_chain.clone(),
497
				chain_spec: chain_spec.cloned_box(),
498
499
500
501
502
503
504
505
506
				deny_unsafe,
				babe: polkadot_rpc::BabeDeps {
					babe_config: babe_config.clone(),
					shared_epoch_changes: shared_epoch_changes.clone(),
					keystore: keystore.clone(),
				},
				grandpa: polkadot_rpc::GrandpaDeps {
					shared_voter_state: shared_voter_state.clone(),
					shared_authority_set: shared_authority_set.clone(),
507
					justification_stream: justification_stream.clone(),
508
					subscription_executor: subscription_executor.clone(),
Jon Häggblad's avatar
Jon Häggblad committed
509
					finality_provider: finality_proof_provider.clone(),
510
				},
511
512
513
514
				beefy: polkadot_rpc::BeefyDeps {
					beefy_commitment_stream: beefy_commitment_stream.clone(),
					subscription_executor,
				},
515
516
			};

517
			polkadot_rpc::create_full(deps).map_err(Into::into)
518
		}
519
520
	};

521
	Ok(service::PartialComponents {
522
523
524
525
526
527
528
		client,
		backend,
		task_manager,
		keystore_container,
		select_chain,
		import_queue,
		transaction_pool,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
529
		other: (rpc_extensions_builder, import_setup, rpc_setup, slot_duration, telemetry),
530
	})
531
532
}

533
534
535
pub struct NewFull<C> {
	pub task_manager: TaskManager,
	pub client: C,
Andronik Ordian's avatar
Andronik Ordian committed
536
	pub overseer_handle: Option<Handle>,
537
538
	pub network: Arc<sc_network::NetworkService<Block, <Block as BlockT>::Hash>>,
	pub rpc_handlers: RpcHandlers,
539
	pub backend: Arc<FullBackend>,
540
541
542
}

impl<C> NewFull<C> {
543
544
	/// Convert the client type using the given `func`.
	pub fn with_client<NC>(self, func: impl FnOnce(C) -> NC) -> NewFull<NC> {
545
546
547
		NewFull {
			client: func(self.client),
			task_manager: self.task_manager,
Andronik Ordian's avatar
Andronik Ordian committed
548
			overseer_handle: self.overseer_handle,
549
550
			network: self.network,
			rpc_handlers: self.rpc_handlers,
551
			backend: self.backend,
552
553
554
555
		}
	}
}

556
/// Is this node a collator?
557
#[derive(Clone)]
558
559
pub enum IsCollator {
	/// This node is a collator.
560
	Yes(CollatorPair),
561
562
563
564
	/// This node is not a collator.
	No,
}

565
566
567
568
569
570
571
572
573
574
impl std::fmt::Debug for IsCollator {
	fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
		use sp_core::Pair;
		match self {
			IsCollator::Yes(pair) => write!(fmt, "Yes({})", pair.public()),
			IsCollator::No => write!(fmt, "No"),
		}
	}
}

575
576
577
impl IsCollator {
	/// Is this a collator?
	fn is_collator(&self) -> bool {
578
		matches!(self, Self::Yes(_))
579
580
581
	}
}

582
/// Returns the active leaves the overseer should start with.
583
async fn active_leaves<RuntimeApi, ExecutorDispatch>(
Andronik Ordian's avatar
Andronik Ordian committed
584
	select_chain: &impl SelectChain<Block>,
585
	client: &FullClient<RuntimeApi, ExecutorDispatch>,
586
587
) -> Result<Vec<BlockInfo>, Error>
where
588
589
590
591
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>
		+ Send
		+ Sync
		+ 'static,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
592
	RuntimeApi::RuntimeApi:
593
		RuntimeApiCollection<StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,
594
	ExecutorDispatch: NativeExecutionDispatch + 'static,
595
{
596
	let best_block = select_chain.best_chain().await?;
597
598
599

	let mut leaves = select_chain
		.leaves()
600
		.await
601
602
603
		.unwrap_or_default()
		.into_iter()
		.filter_map(|hash| {
604
			let number = HeaderBackend::number(client, hash).ok()??;
605
606
607
608
609
610
611
612
613
614

			// Only consider leaves that are in maximum an uncle of the best block.
			if number < best_block.number().saturating_sub(1) {
				return None
			} else if hash == best_block.hash() {
				return None
			};

			let parent_hash = client.header(&BlockId::Hash(hash)).ok()??.parent_hash;

Shawn Tabrizi's avatar
Shawn Tabrizi committed
615
			Some(BlockInfo { hash, parent_hash, number })
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
		})
		.collect::<Vec<_>>();

	// Sort by block number and get the maximum number of leaves
	leaves.sort_by_key(|b| b.number);

	leaves.push(BlockInfo {
		hash: best_block.hash(),
		parent_hash: *best_block.parent_hash(),
		number: *best_block.number(),
	});

	Ok(leaves.into_iter().rev().take(MAX_ACTIVE_LEAVES).collect())
}

631
632
633
634
/// Create a new full node of arbitrary runtime and executor.
///
/// This is an advanced feature and not recommended for general use. Generally, `build_full` is
/// a better choice.
635
pub fn new_full<RuntimeApi, ExecutorDispatch, OverseerGenerator>(
636
	mut config: Configuration,
637
	is_collator: IsCollator,
638
	grandpa_pause: Option<(u32, u32)>,
639
	disable_beefy: bool,
640
	jaeger_agent: Option<std::net::SocketAddr>,
641
	telemetry_worker_handle: Option<TelemetryWorkerHandle>,
642
	program_path: Option<std::path::PathBuf>,
643
	overseer_gen: OverseerGenerator,
644
) -> Result<NewFull<Arc<FullClient<RuntimeApi, ExecutorDispatch>>>, Error>
Shawn Tabrizi's avatar
Shawn Tabrizi committed
645
where
646
647
648
649
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>
		+ Send
		+ Sync
		+ 'static,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
650
	RuntimeApi::RuntimeApi:
651
		RuntimeApiCollection<StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,
652
	ExecutorDispatch: NativeExecutionDispatch + 'static,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
653
	OverseerGenerator: OverseerGen,
654
{
655
656
	use polkadot_node_network_protocol::request_response::IncomingRequest;

657
658
	let role = config.role.clone();
	let force_authoring = config.force_authoring;
659
	let backoff_authoring_blocks = {
660
		let mut backoff = sc_consensus_slots::BackoffAuthoringOnFinalizedHeadLagging::default();
661

662
		if config.chain_spec.is_rococo() || config.chain_spec.is_wococo() {
663
664
665
666
667
668
669
670
			// it's a testnet that's in flux, finality has stalled sometimes due
			// to operational issues and it's annoying to slow down block
			// production to 1 block per hour.
			backoff.max_interval = 10;
		}

		Some(backoff)
	};
671

672
673
674
	let disable_grandpa = config.disable_grandpa;
	let name = config.network.node_name.clone();

675
676
677
678
679
680
681
682
683
684
685
686
687
688
	let basics = new_partial_basics::<RuntimeApi, ExecutorDispatch>(
		&mut config,
		jaeger_agent,
		telemetry_worker_handle,
	)?;

	let prometheus_registry = config.prometheus_registry().cloned();

	let overseer_connector = OverseerConnector::default();
	let overseer_handle = Handle::new(overseer_connector.handle());

	let chain_spec = config.chain_spec.cloned_box();

	let local_keystore = basics.keystore_container.local_keystore();
689
690
	let requires_overseer_for_chain_sel =
		local_keystore.is_some() && (role.is_authority() || is_collator.is_collator());
691
692
693
694
695
696
697

	let select_chain = SelectRelayChain::new(
		basics.backend.clone(),
		overseer_handle.clone(),
		requires_overseer_for_chain_sel,
		polkadot_node_subsystem_util::metrics::Metrics::register(prometheus_registry.as_ref())?,
	);
698

699
	let service::PartialComponents::<_, _, SelectRelayChain<_>, _, _, _> {
700
701
702
		client,
		backend,
		mut task_manager,
703
		keystore_container,
704
		select_chain,
705
706
		import_queue,
		transaction_pool,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
707
		other: (rpc_extensions_builder, import_setup, rpc_setup, slot_duration, mut telemetry),
708
	} = new_partial::<RuntimeApi, ExecutorDispatch, SelectRelayChain<_>>(
709
		&mut config,
710
711
		basics,
		select_chain,
712
	)?;
713

714
	let shared_voter_state = rpc_setup;
715
	let auth_disc_publish_non_global_ips = config.network.allow_non_globals_in_dht;
716

717
718
719
720
	// Note: GrandPa is pushed before the Polkadot-specific protocols. This doesn't change
	// anything in terms of behaviour, but makes the logs more consistent with the other
	// Substrate nodes.
	config.network.extra_sets.push(grandpa::grandpa_peers_set_config());
721

722
	if chain_spec.is_rococo() || chain_spec.is_wococo() {
723
724
725
		config.network.extra_sets.push(beefy_gadget::beefy_peers_set_config());
	}

726
727
	{
		use polkadot_network_bridge::{peer_sets_info, IsAuthority};
Shawn Tabrizi's avatar
Shawn Tabrizi committed
728
		let is_authority = if role.is_authority() { IsAuthority::Yes } else { IsAuthority::No };
729
730
		config.network.extra_sets.extend(peer_sets_info(is_authority));
	}
731

732
733
734
735
736
737
738
739
740
741
742
743
	let (pov_req_receiver, cfg) = IncomingRequest::get_config_receiver();
	config.network.request_response_protocols.push(cfg);
	let (chunk_req_receiver, cfg) = IncomingRequest::get_config_receiver();
	config.network.request_response_protocols.push(cfg);
	let (collation_req_receiver, cfg) = IncomingRequest::get_config_receiver();
	config.network.request_response_protocols.push(cfg);
	let (available_data_req_receiver, cfg) = IncomingRequest::get_config_receiver();
	config.network.request_response_protocols.push(cfg);
	let (statement_req_receiver, cfg) = IncomingRequest::get_config_receiver();
	config.network.request_response_protocols.push(cfg);
	let (dispute_req_receiver, cfg) = IncomingRequest::get_config_receiver();
	config.network.request_response_protocols.push(cfg);
744

745
746
747
748
749
750
	let grandpa_hard_forks = if config.chain_spec.is_kusama() {
		grandpa_support::kusama_hard_forks()
	} else {
		Vec::new()
	};

751
	let warp_sync = Arc::new(grandpa::warp_proof::NetworkProvider::new(
Shawn Tabrizi's avatar
Shawn Tabrizi committed
752
753
		backend.clone(),
		import_setup.1.shared_authority_set().clone(),
754
		grandpa_hard_forks,
755
756
	));

757
	let (network, system_rpc_tx, network_starter) =
758
759
760
761
762
763
764
765
		service::build_network(service::BuildNetworkParams {
			config: &config,
			client: client.clone(),
			transaction_pool: transaction_pool.clone(),
			spawn_handle: task_manager.spawn_handle(),
			import_queue,
			on_demand: None,
			block_announce_validator_builder: None,
766
			warp_sync: Some(warp_sync),
767
768
769
		})?;

	if config.offchain_worker.enabled {
770
		let _ = service::build_offchain_workers(
Shawn Tabrizi's avatar
Shawn Tabrizi committed
771
772
773
774
			&config,
			task_manager.spawn_handle(),
			client.clone(),
			network.clone(),
775
776
		);
	}
777

778
779
780
781
782
783
784
785
786
	let parachains_db = crate::parachains_db::open_creating(
		config.database.path().ok_or(Error::DatabasePathRequired)?.into(),
		crate::parachains_db::CacheSizes::default(),
	)?;

	let availability_config = AvailabilityConfig {
		col_data: crate::parachains_db::REAL_COLUMNS.col_availability_data,
		col_meta: crate::parachains_db::REAL_COLUMNS.col_availability_meta,
	};
787

788
	let approval_voting_config = ApprovalVotingConfig {
789
		col_data: crate::parachains_db::REAL_COLUMNS.col_approval_data,
790
		slot_duration_millis: slot_duration.as_millis() as u64,
791
792
	};

793
	let candidate_validation_config = CandidateValidationConfig {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
794
795
		artifacts_cache_path: config
			.database
796
797
798
799
800
801
802
803
804
			.path()
			.ok_or(Error::DatabasePathRequired)?
			.join("pvf-artifacts"),
		program_path: match program_path {
			None => std::env::current_exe()?,
			Some(p) => p,
		},
	};

Andronik Ordian's avatar
Andronik Ordian committed
805
806
807
808
809
810
811
812
813
	let chain_selection_config = ChainSelectionConfig {
		col_data: crate::parachains_db::REAL_COLUMNS.col_chain_selection_data,
		stagnant_check_interval: chain_selection_subsystem::StagnantCheckInterval::never(),
	};

	let dispute_coordinator_config = DisputeCoordinatorConfig {
		col_data: crate::parachains_db::REAL_COLUMNS.col_dispute_coordinator_data,
	};

814
	let rpc_handlers = service::spawn_tasks(service::SpawnTasksParams {
815
816
817
		config,
		backend: backend.clone(),
		client: client.clone(),
818
		keystore: keystore_container.sync_keystore(),
819
820
821
822
823
824
		network: network.clone(),
		rpc_extensions_builder: Box::new(rpc_extensions_builder),
		transaction_pool: transaction_pool.clone(),
		task_manager: &mut task_manager,
		on_demand: None,
		remote_blockchain: None,
825
		system_rpc_tx,
826
		telemetry: telemetry.as_mut(),
827
	})?;
828

829
	let (block_import, link_half, babe_link, beefy_link) = import_setup;
830
831
832

	let overseer_client = client.clone();
	let spawner = task_manager.spawn_handle();
833
834
835
836
	// Cannot use the `RelayChainSelection`, since that'd require a setup _and running_ overseer
	// which we are about to setup.
	let active_leaves =
		futures::executor::block_on(active_leaves(select_chain.as_longest_chain(), &*client))?;
837

838
839
	let authority_discovery_service = if role.is_authority() || is_collator.is_collator() {
		use futures::StreamExt;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
840
		use sc_network::Event;
841

842
		let authority_discovery_role = if role.is_authority() {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
843
			sc_authority_discovery::Role::PublishAndDiscover(keystore_container.keystore())
844
845
		} else {
			// don't publish our addresses when we're only a collator
846
			sc_authority_discovery::Role::Discover
847
		};
Shawn Tabrizi's avatar
Shawn Tabrizi committed
848
849
850
851
852
853
854
		let dht_event_stream =
			network.event_stream("authority-discovery").filter_map(|e| async move {
				match e {
					Event::Dht(e) => Some(e),
					_ => None,
				}
			});
855
856
857
858
859
		let (worker, service) = sc_authority_discovery::new_worker_and_service_with_config(
			sc_authority_discovery::WorkerConfig {
				publish_non_global_ips: auth_disc_publish_non_global_ips,
				..Default::default()
			},
860
861
862
863
864
865
			client.clone(),
			network.clone(),
			Box::pin(dht_event_stream),
			authority_discovery_role,
			prometheus_registry.clone(),
		);
866

867
868
869
870
871
872
		task_manager.spawn_handle().spawn("authority-discovery-worker", worker.run());
		Some(service)
	} else {
		None
	};

873
874
875
876
	if local_keystore.is_none() {
		tracing::info!("Cannot run as validator without local keystore.");
	}

Shawn Tabrizi's avatar
Shawn Tabrizi committed
877
878
	let maybe_params =
		local_keystore.and_then(move |k| authority_discovery_service.map(|a| (a, k)));
879

Andronik Ordian's avatar
Andronik Ordian committed
880
	let overseer_handle = if let Some((authority_discovery_service, keystore)) = maybe_params {
881
		let (overseer, overseer_handle) = overseer_gen
882
			.generate::<service::SpawnTaskHandle, FullClient<RuntimeApi, ExecutorDispatch>>(
883
				overseer_connector,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
884
885
886
887
888
889
890
				OverseerGenArgs {
					leaves: active_leaves,
					keystore,
					runtime_client: overseer_client.clone(),
					parachains_db,
					network_service: network.clone(),
					authority_discovery_service,
891
892
893
894
895
896
					pov_req_receiver,
					chunk_req_receiver,
					collation_req_receiver,
					available_data_req_receiver,
					statement_req_receiver,
					dispute_req_receiver,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
897
898
899
900
901
902
903
904
905
906
					registry: prometheus_registry.as_ref(),
					spawner,
					is_collator,
					approval_voting_config,
					availability_config,
					candidate_validation_config,
					chain_selection_config,
					dispute_coordinator_config,
				},
			)?;
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
		let handle = Handle::new(overseer_handle.clone());

		{
			let handle = handle.clone();
			task_manager.spawn_essential_handle().spawn_blocking(
				"overseer",
				Box::pin(async move {
					use futures::{pin_mut, select, FutureExt};

					let forward = polkadot_overseer::forward_events(overseer_client, handle);

					let forward = forward.fuse();
					let overseer_fut = overseer.run().fuse();

					pin_mut!(overseer_fut);
					pin_mut!(forward);

					select! {
						_ = forward => (),
						_ = overseer_fut => (),
						complete => (),
					}
				}),
			);
Andronik Ordian's avatar
Andronik Ordian committed
931
932
		}
		Some(handle)
933
	} else {
934
935
936
937
		assert!(
			!requires_overseer_for_chain_sel,
			"Precondition congruence (false) is guaranteed by manual checking. qed"
		);
938
939
		None
	};
940
941
942
943
944

	if role.is_authority() {
		let can_author_with =
			consensus_common::CanAuthorWithNativeVersion::new(client.executor().clone());

945
		let proposer = sc_basic_authorship::ProposerFactory::new(
946
			task_manager.spawn_handle(),
947
948
			client.clone(),
			transaction_pool,
949
			prometheus_registry.as_ref(),
950
			telemetry.as_ref().map(|x| x.handle()),
951
952
		);

953
		let client_clone = client.clone();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
954
955
		let overseer_handle =
			overseer_handle.as_ref().ok_or(Error::AuthoritiesRequireRealOverseer)?.clone();
956
		let slot_duration = babe_link.config().slot_duration();
957
		let babe_config = babe::BabeParams {
958
			keystore: keystore_container.sync_keystore(),
959
960
961
962
963
			client: client.clone(),
			select_chain,
			block_import,
			env: proposer,
			sync_oracle: network.clone(),
964
			justification_sync_link: network.clone(),
965
966
			create_inherent_data_providers: move |parent, ()| {
				let client_clone = client_clone.clone();
Andronik Ordian's avatar
Andronik Ordian committed
967
				let overseer_handle = overseer_handle.clone();
968
969
970
				async move {
					let parachain = polkadot_node_core_parachains_inherent::ParachainsInherentDataProvider::create(
						&*client_clone,
Andronik Ordian's avatar
Andronik Ordian committed
971
						overseer_handle,
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
						parent,
					).await.map_err(|e| Box::new(e))?;

					let uncles = sc_consensus_uncles::create_uncles_inherent_data_provider(
						&*client_clone,
						parent,
					)?;

					let timestamp = sp_timestamp::InherentDataProvider::from_system_time();

					let slot =
						sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_duration(
							*timestamp,
							slot_duration,
						);

					Ok((timestamp, slot, uncles, parachain))
				}
			},
991
			force_authoring,
992
			backoff_authoring_blocks,
993
994
			babe_link,
			can_author_with,
995
			block_proposal_slot_portion: babe::SlotProportion::new(2f32 / 3f32),
996
			max_block_proposal_slot_portion: None,
997
			telemetry: telemetry.as_ref().map(|x| x.handle()),
998
		};
999

1000
1001
1002
		let babe = babe::start_babe(babe_config)?;
		task_manager.spawn_essential_handle().spawn_blocking("babe", babe);
	}
1003

Andreas Doerr's avatar
Andreas Doerr committed
1004
1005
	// if the node isn't actively participating in consensus then it doesn't
	// need a keystore, regardless of which protocol we use below.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1006
1007
	let keystore_opt =
		if role.is_authority() { Some(keystore_container.sync_keystore()) } else { None };
Andreas Doerr's avatar
Andreas Doerr committed
1008

1009
	// We currently only run the BEEFY gadget on the Rococo and Wococo testnets.
1010
	if !disable_beefy && (chain_spec.is_rococo() || chain_spec.is_wococo()) {
Andreas Doerr's avatar
Andreas Doerr committed
1011
1012
1013
1014
1015
1016
1017
1018
1019
		let beefy_params = beefy_gadget::BeefyParams {
			client: client.clone(),
			backend: backend.clone(),
			key_store: keystore_opt.clone(),
			network: network.clone(),
			signed_commitment_sender: beefy_link,
			min_block_delta: if chain_spec.is_wococo() { 4 } else { 8 },
			prometheus_registry: prometheus_registry.clone(),
		};
1020

Shawn Tabrizi's avatar
Shawn Tabrizi committed
1021
		let gadget = beefy_gadget::start_beefy_gadget::<_, _, _, _>(beefy_params);
1022

1023
1024
1025
1026
1027
1028
1029
		// Wococo's purpose is to be a testbed for BEEFY, so if it fails we'll
		// bring the node down with it to make sure it is noticed.
		if chain_spec.is_wococo() {
			task_manager.spawn_essential_handle().spawn_blocking("beefy-gadget", gadget);
		} else {
			task_manager.spawn_handle().spawn_blocking("beefy-gadget", gadget);
		}
1030
1031
	}

1032
1033
1034
1035
1036
1037
	let config = grandpa::Config {
		// FIXME substrate#1578 make this available through chainspec
		gossip_duration: Duration::from_millis(1000),
		justification_period: 512,
		name: Some(name),
		observer_enabled: false,
1038
		keystore: keystore_opt,
1039
		local_role: role,
1040
		telemetry: telemetry.as_ref().map(|x| x.handle()),
1041
	};
1042

1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
	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.

		// 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.
1055
1056
		let builder = grandpa::VotingRulesBuilder::default();

1057
1058
		let voting_rule = match grandpa_pause {
			Some((block, delay)) => {
1059
1060
1061
1062
				info!(
					block_number = %block,
					delay = %delay,
					"GRANDPA scheduled voting pause set for block #{} with a duration of {} blocks.",
1063
1064
1065
					block,
					delay,
				);
1066

Shawn Tabrizi's avatar
Shawn Tabrizi committed
1067
1068
				builder.add(grandpa_support::PauseAfterBlockFor(block, delay)).build()
			},
1069
			None => builder.build(),
1070
1071
		};

1072
1073
1074
1075
1076
		let grandpa_config = grandpa::GrandpaParams {
			config,
			link: link_half,
			network: network.clone(),
			voting_rule,
1077
			prometheus_registry: prometheus_registry.clone(),
1078
			shared_voter_state,
1079
			telemetry: telemetry.as_ref().map(|x| x.handle()),
1080
1081
		};

Shawn Tabrizi's avatar
Shawn Tabrizi committed
1082
1083
1084
		task_manager
			.spawn_essential_handle()
			.spawn_blocking("grandpa-voter", grandpa::run_grandpa_voter(grandpa_config)?);
1085
	}
1086

1087
1088
	network_starter.start_network();

Shawn Tabrizi's avatar
Shawn Tabrizi committed
1089
	Ok(NewFull { task_manager, client, overseer_handle, network, rpc_handlers, backend })
1090
1091
}

1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
macro_rules! chain_ops {
	($config:expr, $jaeger_agent:expr, $telemetry_worker_handle:expr; $scope:ident, $executor:ident, $variant:ident) => {{
		let telemetry_worker_handle = $telemetry_worker_handle;
		let jaeger_agent = $jaeger_agent;
		let mut config = $config;
		let basics = new_partial_basics::<$scope::RuntimeApi, $executor>(
			config,
			jaeger_agent,
			telemetry_worker_handle,
		)?;

		use ::sc_consensus::LongestChain;
		// use the longest chain selection, since there is no overseer available
		let chain_selection = LongestChain::new(basics.backend.clone());

		let service::PartialComponents { client, backend, import_queue, task_manager, .. } =
			new_partial::<$scope::RuntimeApi, $executor, LongestChain<_, Block>>(
				&mut config,
				basics,
				chain_selection,
			)?;
		Ok((Arc::new(Client::$variant(client)), backend, import_queue, task_manager))
	}};
}

1117
/// Builds a new object suitable for chain operations.