referrerpolicy=no-referrer-when-downgrade

cumulus_test_service/
lib.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3
4// Cumulus is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Cumulus is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Cumulus.  If not, see <http://www.gnu.org/licenses/>.
16
17//! Crate used for testing with Cumulus.
18
19#![warn(missing_docs)]
20
21/// Utilities used for benchmarking
22pub mod bench_utils;
23
24pub mod chain_spec;
25
26use cumulus_client_collator::service::CollatorService;
27use cumulus_client_consensus_aura::{
28	collators::{
29		lookahead::{self as aura, Params as AuraParams},
30		slot_based::{
31			self as slot_based, Params as SlotBasedParams, SlotBasedBlockImport,
32			SlotBasedBlockImportHandle,
33		},
34	},
35	ImportQueueParams,
36};
37use prometheus::Registry;
38use runtime::AccountId;
39use sc_executor::{HeapAllocStrategy, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY};
40use sp_consensus_aura::sr25519::AuthorityPair;
41use std::{
42	collections::HashSet,
43	future::Future,
44	net::{Ipv4Addr, SocketAddr, SocketAddrV4},
45	time::Duration,
46};
47use url::Url;
48
49use crate::runtime::Weight;
50use cumulus_client_cli::{CollatorOptions, RelayChainMode};
51use cumulus_client_consensus_common::ParachainBlockImport as TParachainBlockImport;
52use cumulus_client_pov_recovery::{RecoveryDelayRange, RecoveryHandle};
53use cumulus_client_service::{
54	build_network, prepare_node_config, start_relay_chain_tasks, BuildNetworkParams,
55	CollatorSybilResistance, DARecoveryProfile, ParachainTracingExecuteBlock,
56	StartRelayChainTasksParams,
57};
58use cumulus_primitives_core::{relay_chain::ValidationCode, GetParachainInfo, ParaId};
59use cumulus_relay_chain_inprocess_interface::RelayChainInProcessInterface;
60use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult};
61use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node_with_rpc;
62
63use cumulus_test_runtime::{Hash, NodeBlock as Block, RuntimeApi};
64
65use frame_system_rpc_runtime_api::AccountNonceApi;
66use polkadot_node_subsystem::{errors::RecoveryError, messages::AvailabilityRecoveryMessage};
67use polkadot_overseer::Handle as OverseerHandle;
68use polkadot_primitives::{CandidateHash, CollatorPair};
69use polkadot_service::ProvideRuntimeApi;
70use sc_consensus::ImportQueue;
71use sc_network::{
72	config::{FullNetworkConfiguration, TransportConfig},
73	multiaddr,
74	service::traits::NetworkService,
75	NetworkBackend, NetworkBlock, NetworkStateInfo, PeerId,
76};
77use sc_service::{
78	config::{
79		BlocksPruning, DatabaseSource, ExecutorConfiguration, KeystoreConfig, MultiaddrWithPeerId,
80		NetworkConfiguration, OffchainWorkerConfig, PruningMode, RpcBatchRequestConfig,
81		RpcConfiguration, RpcEndpoint, WasmExecutionMethod,
82	},
83	BasePath, ChainSpec as ChainSpecService, Configuration, Error as ServiceError,
84	PartialComponents, Role, RpcHandlers, TFullBackend, TFullClient, TaskManager,
85};
86use sp_arithmetic::traits::SaturatedConversion;
87use sp_blockchain::HeaderBackend;
88use sp_core::Pair;
89use sp_keyring::Sr25519Keyring;
90use sp_runtime::{codec::Encode, generic, MultiAddress};
91use sp_state_machine::BasicExternalities;
92use std::sync::Arc;
93use substrate_test_client::{
94	BlockchainEventsExt, RpcHandlersExt, RpcTransactionError, RpcTransactionOutput,
95};
96
97pub use chain_spec::*;
98pub use cumulus_test_runtime as runtime;
99pub use sp_keyring::Sr25519Keyring as Keyring;
100
101const LOG_TARGET: &str = "cumulus-test-service";
102
103/// The signature of the announce block fn.
104pub type AnnounceBlockFn = Arc<dyn Fn(Hash, Option<Vec<u8>>) + Send + Sync>;
105
106type HostFunctions =
107	(sp_io::SubstrateHostFunctions, cumulus_client_service::storage_proof_size::HostFunctions);
108/// The client type being used by the test service.
109pub type Client = TFullClient<runtime::NodeBlock, runtime::RuntimeApi, WasmExecutor<HostFunctions>>;
110
111/// The backend type being used by the test service.
112pub type Backend = TFullBackend<Block>;
113
114/// The block-import type being used by the test service.
115pub type ParachainBlockImport =
116	TParachainBlockImport<Block, SlotBasedBlockImport<Block, Arc<Client>, Client>, Backend>;
117
118/// Transaction pool type used by the test service
119pub type TransactionPool = Arc<sc_transaction_pool::TransactionPoolHandle<Block, Client>>;
120
121/// Recovery handle that fails regularly to simulate unavailable povs.
122pub struct FailingRecoveryHandle {
123	overseer_handle: OverseerHandle,
124	counter: u32,
125	failed_hashes: HashSet<CandidateHash>,
126}
127
128impl FailingRecoveryHandle {
129	/// Create a new FailingRecoveryHandle
130	pub fn new(overseer_handle: OverseerHandle) -> Self {
131		Self { overseer_handle, counter: 0, failed_hashes: Default::default() }
132	}
133}
134
135#[async_trait::async_trait]
136impl RecoveryHandle for FailingRecoveryHandle {
137	async fn send_recovery_msg(
138		&mut self,
139		message: AvailabilityRecoveryMessage,
140		origin: &'static str,
141	) {
142		let AvailabilityRecoveryMessage::RecoverAvailableData(ref receipt, _, _, _, _) = message;
143		let candidate_hash = receipt.hash();
144
145		// For every 3rd block we immediately signal unavailability to trigger
146		// a retry. The same candidate is never failed multiple times to ensure progress.
147		if self.counter.is_multiple_of(3) && self.failed_hashes.insert(candidate_hash) {
148			tracing::info!(target: LOG_TARGET, ?candidate_hash, "Failing pov recovery.");
149
150			let AvailabilityRecoveryMessage::RecoverAvailableData(_, _, _, _, back_sender) =
151				message;
152			back_sender
153				.send(Err(RecoveryError::Unavailable))
154				.expect("Return channel should work here.");
155		} else {
156			self.overseer_handle.send_msg(message, origin).await;
157		}
158		self.counter += 1;
159	}
160}
161
162/// Assembly of PartialComponents (enough to run chain ops subcommands)
163pub type Service = PartialComponents<
164	Client,
165	Backend,
166	(),
167	sc_consensus::import_queue::BasicQueue<Block>,
168	sc_transaction_pool::TransactionPoolHandle<Block, Client>,
169	(ParachainBlockImport, SlotBasedBlockImportHandle<Block>),
170>;
171
172/// Starts a `ServiceBuilder` for a full service.
173///
174/// Use this macro if you don't actually need the full service, but just the builder in order to
175/// be able to perform chain operations.
176pub fn new_partial(
177	config: &mut Configuration,
178	enable_import_proof_record: bool,
179) -> Result<Service, sc_service::Error> {
180	let heap_pages = config
181		.executor
182		.default_heap_pages
183		.map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static { extra_pages: h as _ });
184
185	let executor = WasmExecutor::builder()
186		.with_execution_method(config.executor.wasm_method)
187		.with_onchain_heap_alloc_strategy(heap_pages)
188		.with_offchain_heap_alloc_strategy(heap_pages)
189		.with_max_runtime_instances(config.executor.max_runtime_instances)
190		.with_runtime_cache_size(config.executor.runtime_cache_size)
191		.build();
192
193	let (client, backend, keystore_container, task_manager) =
194		sc_service::new_full_parts_record_import::<Block, RuntimeApi, _>(
195			config,
196			None,
197			executor,
198			enable_import_proof_record,
199			Default::default(),
200		)?;
201	let client = Arc::new(client);
202
203	let (block_import, block_import_handle) =
204		SlotBasedBlockImport::new(client.clone(), client.clone());
205	let block_import = ParachainBlockImport::new(block_import, backend.clone());
206
207	let transaction_pool = Arc::from(
208		sc_transaction_pool::Builder::new(
209			task_manager.spawn_essential_handle(),
210			client.clone(),
211			config.role.is_authority().into(),
212		)
213		.with_options(config.transaction_pool.clone())
214		.with_prometheus(config.prometheus_registry())
215		.build(),
216	);
217
218	let slot_duration = sc_consensus_aura::slot_duration(&*client)?;
219	let import_queue = cumulus_client_consensus_aura::import_queue::<AuthorityPair, _, _, _, _, _>(
220		ImportQueueParams {
221			block_import: block_import.clone(),
222			client: client.clone(),
223			create_inherent_data_providers: move |_, ()| async move {
224				let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
225
226				let slot =
227					sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
228						*timestamp,
229						slot_duration,
230					);
231
232				Ok((slot, timestamp))
233			},
234			spawner: &task_manager.spawn_essential_handle(),
235			registry: None,
236			telemetry: None,
237		},
238	)?;
239
240	let params = PartialComponents {
241		backend,
242		client,
243		import_queue,
244		keystore_container,
245		task_manager,
246		transaction_pool,
247		select_chain: (),
248		other: (block_import, block_import_handle),
249	};
250
251	Ok(params)
252}
253
254async fn build_relay_chain_interface(
255	relay_chain_config: Configuration,
256	parachain_prometheus_registry: Option<&Registry>,
257	collator_key: Option<CollatorPair>,
258	collator_options: CollatorOptions,
259	task_manager: &mut TaskManager,
260) -> RelayChainResult<(Arc<dyn RelayChainInterface + 'static>, PeerId)> {
261	let relay_chain_node = match collator_options.relay_chain_mode {
262		cumulus_client_cli::RelayChainMode::Embedded => polkadot_test_service::new_full(
263			relay_chain_config,
264			if let Some(ref key) = collator_key {
265				polkadot_service::IsParachainNode::Collator(key.clone())
266			} else {
267				polkadot_service::IsParachainNode::Collator(CollatorPair::generate().0)
268			},
269			None,
270			polkadot_service::CollatorOverseerGen,
271			Some("Relaychain"),
272		)
273		.map_err(|e| RelayChainError::Application(Box::new(e) as Box<_>))?,
274		cumulus_client_cli::RelayChainMode::ExternalRpc(rpc_target_urls) => {
275			return build_minimal_relay_chain_node_with_rpc(
276				relay_chain_config,
277				parachain_prometheus_registry,
278				task_manager,
279				rpc_target_urls,
280			)
281			.await
282			.map(|r| (r.0, r.2.local_peer_id()))
283		},
284	};
285
286	let relay_chain_peer_id = relay_chain_node.network.local_peer_id();
287
288	task_manager.add_child(relay_chain_node.task_manager);
289	tracing::info!("Using inprocess node.");
290	Ok((
291		Arc::new(RelayChainInProcessInterface::new(
292			relay_chain_node.client.clone(),
293			relay_chain_node.backend.clone(),
294			relay_chain_node.sync_service.clone(),
295			relay_chain_node.overseer_handle.ok_or(RelayChainError::GenericError(
296				"Overseer should be running in full node.".to_string(),
297			))?,
298		)),
299		relay_chain_peer_id,
300	))
301}
302
303/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.
304///
305/// This is the actual implementation that is abstract over the executor and the runtime api.
306#[sc_tracing::logging::prefix_logs_with("Parachain")]
307pub async fn start_node_impl<RB, Net: NetworkBackend<Block, Hash>>(
308	parachain_config: Configuration,
309	collator_key: Option<CollatorPair>,
310	relay_chain_config: Configuration,
311	wrap_announce_block: Option<Box<dyn FnOnce(AnnounceBlockFn) -> AnnounceBlockFn>>,
312	fail_pov_recovery: bool,
313	rpc_ext_builder: RB,
314	collator_options: CollatorOptions,
315	proof_recording_during_import: bool,
316	use_slot_based_collator: bool,
317	collator_reserved_slots: usize,
318) -> sc_service::error::Result<(
319	TaskManager,
320	Arc<Client>,
321	Arc<dyn NetworkService>,
322	RpcHandlers,
323	TransactionPool,
324	Arc<Backend>,
325)>
326where
327	RB: Fn(Arc<Client>) -> Result<jsonrpsee::RpcModule<()>, sc_service::Error> + Send + 'static,
328{
329	let mut parachain_config = prepare_node_config(parachain_config);
330
331	let params = new_partial(&mut parachain_config, proof_recording_during_import)?;
332
333	let transaction_pool = params.transaction_pool.clone();
334	let mut task_manager = params.task_manager;
335
336	let client = params.client.clone();
337	let backend = params.backend.clone();
338
339	let (block_import, block_import_handle) = params.other;
340	let (relay_chain_interface, relay_chain_peer_id) = build_relay_chain_interface(
341		relay_chain_config,
342		parachain_config.prometheus_registry(),
343		collator_key.clone(),
344		collator_options.clone(),
345		&mut task_manager,
346	)
347	.await
348	.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;
349
350	let import_queue_service = params.import_queue.service();
351	let prometheus_registry = parachain_config.prometheus_registry().cloned();
352	let net_config = FullNetworkConfiguration::<Block, Hash, Net>::new(
353		&parachain_config.network,
354		prometheus_registry.clone(),
355	);
356
357	let best_hash = client.chain_info().best_hash;
358	let para_id = client
359		.runtime_api()
360		.parachain_id(best_hash)
361		.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;
362	tracing::info!("Parachain id: {:?}", para_id);
363
364	let (network, system_rpc_tx, tx_handler_controller, sync_service) =
365		build_network(BuildNetworkParams {
366			parachain_config: &parachain_config,
367			net_config,
368			client: client.clone(),
369			transaction_pool: transaction_pool.clone(),
370			para_id,
371			spawn_handle: task_manager.spawn_handle(),
372			spawn_essential_handle: task_manager.spawn_essential_handle(),
373			relay_chain_interface: relay_chain_interface.clone(),
374			import_queue: params.import_queue,
375			metrics: Net::register_notification_metrics(
376				parachain_config.prometheus_config.as_ref().map(|config| &config.registry),
377			),
378			sybil_resistance_level: CollatorSybilResistance::Resistant,
379		})
380		.await?;
381
382	let keystore = params.keystore_container.keystore();
383
384	if collator_key.is_some() && collator_reserved_slots > 0 {
385		cumulus_client_collator_discovery::start_collator_discovery(
386			cumulus_client_collator_discovery::StartCollatorDiscoveryParams {
387				max_reserved: collator_reserved_slots,
388				client: client.clone(),
389				authority_discovery: client.clone(),
390				network: network.clone(),
391				sync_service: sync_service.clone(),
392				network_event_stream: network.event_stream("para-authority-discovery"),
393				keystore: keystore.clone(),
394				genesis_hash: client.chain_info().genesis_hash,
395				fork_id: parachain_config.chain_spec.fork_id().map(ToString::to_string),
396				publish_non_global_ips: parachain_config.network.allow_non_globals_in_dht,
397				public_addresses: parachain_config.network.public_addresses.clone(),
398				persisted_cache_directory: parachain_config.network.net_config_path.clone(),
399				prometheus_registry: prometheus_registry.clone(),
400				spawn_handle: task_manager.spawn_handle(),
401			},
402		)
403		.map_err(|e| sc_service::Error::Application(Box::new(e)))?;
404	}
405
406	let rpc_builder = {
407		let client = client.clone();
408		Box::new(move |_| rpc_ext_builder(client.clone()))
409	};
410
411	let rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
412		rpc_builder,
413		client: client.clone(),
414		transaction_pool: transaction_pool.clone(),
415		task_manager: &mut task_manager,
416		config: parachain_config,
417		keystore: keystore.clone(),
418		backend: backend.clone(),
419		network: network.clone(),
420		sync_service: sync_service.clone(),
421		system_rpc_tx,
422		tx_handler_controller,
423		telemetry: None,
424		tracing_execute_block: Some(Arc::new(ParachainTracingExecuteBlock::new(client.clone()))),
425	})?;
426
427	let announce_block = {
428		let sync_service = sync_service.clone();
429		Arc::new(move |hash, data| sync_service.announce_block(hash, data))
430	};
431
432	let announce_block = wrap_announce_block
433		.map(|w| (w)(announce_block.clone()))
434		.unwrap_or_else(|| announce_block);
435
436	let overseer_handle = relay_chain_interface
437		.overseer_handle()
438		.map_err(|e| sc_service::Error::Application(Box::new(e)))?;
439
440	let recovery_handle: Box<dyn RecoveryHandle> = if fail_pov_recovery {
441		Box::new(FailingRecoveryHandle::new(overseer_handle.clone()))
442	} else {
443		Box::new(overseer_handle.clone())
444	};
445	let relay_chain_slot_duration = Duration::from_secs(6);
446
447	start_relay_chain_tasks(StartRelayChainTasksParams {
448		client: client.clone(),
449		announce_block: announce_block.clone(),
450		para_id,
451		relay_chain_interface: relay_chain_interface.clone(),
452		task_manager: &mut task_manager,
453		// Increase speed of recovery for testing purposes.
454		da_recovery_profile: DARecoveryProfile::Other(RecoveryDelayRange {
455			min: Duration::from_secs(1),
456			max: Duration::from_secs(5),
457		}),
458		import_queue: import_queue_service,
459		relay_chain_slot_duration,
460		recovery_handle,
461		sync_service: sync_service.clone(),
462		prometheus_registry: None,
463	})?;
464
465	let collator_peer_id = relay_chain_peer_id;
466	if let Some(collator_key) = collator_key {
467		let proposer = sc_basic_authorship::ProposerFactory::new(
468			task_manager.spawn_handle(),
469			client.clone(),
470			transaction_pool.clone(),
471			prometheus_registry.as_ref(),
472			None,
473		);
474
475		let collator_service = CollatorService::new(
476			client.clone(),
477			Arc::new(task_manager.spawn_handle()),
478			announce_block,
479			client.clone(),
480		);
481
482		let client_for_aura = client.clone();
483
484		if use_slot_based_collator {
485			tracing::info!(target: LOG_TARGET, "Starting block authoring with slot based authoring.");
486			let params = SlotBasedParams {
487				create_inherent_data_providers: move |_, ()| async move { Ok(()) },
488				block_import,
489				para_client: client.clone(),
490				para_backend: backend.clone(),
491				relay_client: relay_chain_interface,
492				code_hash_provider: move |block_hash| {
493					client_for_aura.code_at(block_hash).ok().map(|c| ValidationCode::from(c).hash())
494				},
495				keystore,
496				collator_key,
497				relay_chain_slot_duration,
498				para_id,
499				proposer,
500				collator_service,
501				reinitialize: false,
502				slot_offset: Duration::from_secs(1),
503				block_import_handle,
504				spawner: task_manager.spawn_essential_handle(),
505				export_pov: None,
506				max_pov_percentage: None,
507				collator_peer_id,
508			};
509
510			slot_based::run::<Block, AuthorityPair, _, _, _, _, _, _, _, _, _>(params);
511		} else {
512			tracing::info!(target: LOG_TARGET, "Starting block authoring with lookahead collator.");
513			let params = AuraParams {
514				create_inherent_data_providers: move |_, ()| async move { Ok(()) },
515				block_import,
516				para_client: client.clone(),
517				para_backend: backend.clone(),
518				relay_client: relay_chain_interface,
519				code_hash_provider: move |block_hash| {
520					client_for_aura.code_at(block_hash).ok().map(|c| ValidationCode::from(c).hash())
521				},
522				keystore,
523				collator_key,
524				collator_peer_id,
525				para_id,
526				overseer_handle,
527				relay_chain_slot_duration,
528				proposer,
529				collator_service,
530				authoring_duration: Duration::from_millis(2000),
531				reinitialize: false,
532				max_pov_percentage: None,
533			};
534
535			let fut = aura::run::<Block, AuthorityPair, _, _, _, _, _, _, _, _>(params);
536			task_manager.spawn_essential_handle().spawn("aura", None, fut);
537		}
538	}
539
540	Ok((task_manager, client, network, rpc_handlers, transaction_pool, backend))
541}
542
543/// A Cumulus test node instance used for testing.
544pub struct TestNode {
545	/// TaskManager's instance.
546	pub task_manager: TaskManager,
547	/// Client's instance.
548	pub client: Arc<Client>,
549	/// Node's network.
550	pub network: Arc<dyn NetworkService>,
551	/// The `MultiaddrWithPeerId` to this node. This is useful if you want to pass it as "boot
552	/// node" to other nodes.
553	pub addr: MultiaddrWithPeerId,
554	/// RPCHandlers to make RPC queries.
555	pub rpc_handlers: RpcHandlers,
556	/// Node's transaction pool
557	pub transaction_pool: TransactionPool,
558	/// Node's backend
559	pub backend: Arc<Backend>,
560}
561
562/// A builder to create a [`TestNode`].
563pub struct TestNodeBuilder {
564	para_id: ParaId,
565	tokio_handle: tokio::runtime::Handle,
566	key: Sr25519Keyring,
567	collator_key: Option<CollatorPair>,
568	parachain_nodes: Vec<MultiaddrWithPeerId>,
569	parachain_nodes_exclusive: bool,
570	relay_chain_nodes: Vec<MultiaddrWithPeerId>,
571	wrap_announce_block: Option<Box<dyn FnOnce(AnnounceBlockFn) -> AnnounceBlockFn>>,
572	storage_update_func_parachain: Option<Box<dyn Fn()>>,
573	storage_update_func_relay_chain: Option<Box<dyn Fn()>>,
574	relay_chain_mode: RelayChainMode,
575	endowed_accounts: Vec<AccountId>,
576	record_proof_during_import: bool,
577}
578
579impl TestNodeBuilder {
580	/// Create a new instance of `Self`.
581	///
582	/// `para_id` - The parachain id this node is running for.
583	/// `tokio_handle` - The tokio handler to use.
584	/// `key` - The key that will be used to generate the name and that will be passed as
585	/// `dev_seed`.
586	pub fn new(para_id: ParaId, tokio_handle: tokio::runtime::Handle, key: Sr25519Keyring) -> Self {
587		TestNodeBuilder {
588			key,
589			para_id,
590			tokio_handle,
591			collator_key: None,
592			parachain_nodes: Vec::new(),
593			parachain_nodes_exclusive: false,
594			relay_chain_nodes: Vec::new(),
595			wrap_announce_block: None,
596			storage_update_func_parachain: None,
597			storage_update_func_relay_chain: None,
598			endowed_accounts: Default::default(),
599			relay_chain_mode: RelayChainMode::Embedded,
600			record_proof_during_import: true,
601		}
602	}
603
604	/// Enable collator for this node.
605	pub fn enable_collator(mut self) -> Self {
606		let collator_key = CollatorPair::generate().0;
607		self.collator_key = Some(collator_key);
608		self
609	}
610
611	/// Instruct the node to exclusively connect to registered parachain nodes.
612	///
613	/// Parachain nodes can be registered using [`Self::connect_to_parachain_node`] and
614	/// [`Self::connect_to_parachain_nodes`].
615	pub fn exclusively_connect_to_registered_parachain_nodes(mut self) -> Self {
616		self.parachain_nodes_exclusive = true;
617		self
618	}
619
620	/// Make the node connect to the given parachain node.
621	///
622	/// By default the node will not be connected to any node or will be able to discover any other
623	/// node.
624	pub fn connect_to_parachain_node(mut self, node: &TestNode) -> Self {
625		self.parachain_nodes.push(node.addr.clone());
626		self
627	}
628
629	/// Make the node connect to the given parachain nodes.
630	///
631	/// By default the node will not be connected to any node or will be able to discover any other
632	/// node.
633	pub fn connect_to_parachain_nodes<'a>(
634		mut self,
635		nodes: impl IntoIterator<Item = &'a TestNode>,
636	) -> Self {
637		self.parachain_nodes.extend(nodes.into_iter().map(|n| n.addr.clone()));
638		self
639	}
640
641	/// Make the node connect to the given relay chain node.
642	///
643	/// By default the node will not be connected to any node or will be able to discover any other
644	/// node.
645	pub fn connect_to_relay_chain_node(
646		mut self,
647		node: &polkadot_test_service::PolkadotTestNode,
648	) -> Self {
649		self.relay_chain_nodes.push(node.addr.clone());
650		self
651	}
652
653	/// Make the node connect to the given relay chain nodes.
654	///
655	/// By default the node will not be connected to any node or will be able to discover any other
656	/// node.
657	pub fn connect_to_relay_chain_nodes<'a>(
658		mut self,
659		nodes: impl IntoIterator<Item = &'a polkadot_test_service::PolkadotTestNode>,
660	) -> Self {
661		self.relay_chain_nodes.extend(nodes.into_iter().map(|n| n.addr.clone()));
662		self
663	}
664
665	/// Wrap the announce block function of this node.
666	pub fn wrap_announce_block(
667		mut self,
668		wrap: impl FnOnce(AnnounceBlockFn) -> AnnounceBlockFn + 'static,
669	) -> Self {
670		self.wrap_announce_block = Some(Box::new(wrap));
671		self
672	}
673
674	/// Allows accessing the parachain storage before the test node is built.
675	pub fn update_storage_parachain(mut self, updater: impl Fn() + 'static) -> Self {
676		self.storage_update_func_parachain = Some(Box::new(updater));
677		self
678	}
679
680	/// Allows accessing the relay chain storage before the test node is built.
681	pub fn update_storage_relay_chain(mut self, updater: impl Fn() + 'static) -> Self {
682		self.storage_update_func_relay_chain = Some(Box::new(updater));
683		self
684	}
685
686	/// Connect to full node via RPC.
687	pub fn use_external_relay_chain_node_at_url(mut self, network_address: Url) -> Self {
688		self.relay_chain_mode = RelayChainMode::ExternalRpc(vec![network_address]);
689		self
690	}
691
692	/// Connect to full node via RPC.
693	pub fn use_external_relay_chain_node_at_port(mut self, port: u16) -> Self {
694		let mut localhost_url =
695			Url::parse("ws://localhost").expect("Should be able to parse localhost Url");
696		localhost_url.set_port(Some(port)).expect("Should be able to set port");
697		self.relay_chain_mode = RelayChainMode::ExternalRpc(vec![localhost_url]);
698		self
699	}
700
701	/// Accounts which will have an initial balance.
702	pub fn endowed_accounts(mut self, accounts: Vec<AccountId>) -> TestNodeBuilder {
703		self.endowed_accounts = accounts;
704		self
705	}
706
707	/// Record proofs during import.
708	pub fn import_proof_recording(mut self, should_record_proof: bool) -> TestNodeBuilder {
709		self.record_proof_during_import = should_record_proof;
710		self
711	}
712
713	/// Build the [`TestNode`].
714	pub async fn build(self) -> TestNode {
715		let parachain_config = node_config(
716			self.storage_update_func_parachain.unwrap_or_else(|| Box::new(|| ())),
717			self.tokio_handle.clone(),
718			self.key,
719			self.parachain_nodes,
720			self.parachain_nodes_exclusive,
721			self.para_id,
722			self.collator_key.is_some(),
723			self.endowed_accounts,
724		)
725		.expect("could not generate Configuration");
726
727		let mut relay_chain_config = polkadot_test_service::node_config(
728			self.storage_update_func_relay_chain.unwrap_or_else(|| Box::new(|| ())),
729			self.tokio_handle,
730			self.key,
731			self.relay_chain_nodes,
732			false,
733		);
734
735		let collator_options = CollatorOptions {
736			relay_chain_mode: self.relay_chain_mode,
737			embedded_dht_bootnode: true,
738			dht_bootnode_discovery: true,
739		};
740
741		relay_chain_config.network.node_name =
742			format!("{} (relay chain)", relay_chain_config.network.node_name);
743
744		let (task_manager, client, network, rpc_handlers, transaction_pool, backend) =
745			match relay_chain_config.network.network_backend {
746				sc_network::config::NetworkBackendType::Libp2p => {
747					start_node_impl::<_, sc_network::NetworkWorker<_, _>>(
748						parachain_config,
749						self.collator_key,
750						relay_chain_config,
751						self.wrap_announce_block,
752						false,
753						|_| Ok(jsonrpsee::RpcModule::new(())),
754						collator_options,
755						self.record_proof_during_import,
756						false,
757						0,
758					)
759					.await
760					.expect("could not create Cumulus test service")
761				},
762				sc_network::config::NetworkBackendType::Litep2p => {
763					start_node_impl::<_, sc_network::Litep2pNetworkBackend>(
764						parachain_config,
765						self.collator_key,
766						relay_chain_config,
767						self.wrap_announce_block,
768						false,
769						|_| Ok(jsonrpsee::RpcModule::new(())),
770						collator_options,
771						self.record_proof_during_import,
772						false,
773						0,
774					)
775					.await
776					.expect("could not create Cumulus test service")
777				},
778			};
779		let peer_id = network.local_peer_id();
780		let multiaddr = polkadot_test_service::get_listen_address(network.clone()).await;
781		let addr = MultiaddrWithPeerId { multiaddr, peer_id };
782
783		TestNode { task_manager, client, network, addr, rpc_handlers, transaction_pool, backend }
784	}
785}
786
787/// Create a Cumulus `Configuration`.
788///
789/// By default a TCP socket will be used, therefore you need to provide nodes if you want the
790/// node to be connected to other nodes.
791///
792/// If `nodes_exclusive` is `true`, the node will only connect to the given `nodes` and not to any
793/// other node.
794///
795/// The `storage_update_func` can be used to make adjustments to the runtime genesis.
796pub fn node_config(
797	storage_update_func: impl Fn(),
798	tokio_handle: tokio::runtime::Handle,
799	key: Sr25519Keyring,
800	nodes: Vec<MultiaddrWithPeerId>,
801	nodes_exclusive: bool,
802	para_id: ParaId,
803	is_collator: bool,
804	endowed_accounts: Vec<AccountId>,
805) -> Result<Configuration, ServiceError> {
806	let base_path = BasePath::new_temp_dir()?;
807	let root = base_path.path().join(format!("cumulus_test_service_{}", key));
808	let role = if is_collator { Role::Authority } else { Role::Full };
809	let key_seed = key.to_seed();
810	let mut spec = Box::new(chain_spec::get_chain_spec_with_extra_endowed(
811		Some(para_id),
812		endowed_accounts,
813		cumulus_test_runtime::WASM_BINARY.expect("WASM binary was not built, please build it!"),
814	));
815
816	let mut storage = spec.as_storage_builder().build_storage().expect("could not build storage");
817
818	BasicExternalities::execute_with_storage(&mut storage, storage_update_func);
819	spec.set_storage(storage);
820
821	let mut network_config = NetworkConfiguration::new(
822		format!("{} (parachain)", key_seed),
823		"network/test/0.1",
824		Default::default(),
825		None,
826	);
827
828	if nodes_exclusive {
829		network_config.default_peers_set.reserved_nodes = nodes;
830		network_config.default_peers_set.non_reserved_mode =
831			sc_network::config::NonReservedPeerMode::Deny;
832	} else {
833		network_config.boot_nodes = nodes;
834	}
835
836	network_config.allow_non_globals_in_dht = true;
837
838	let addr: multiaddr::Multiaddr = "/ip4/127.0.0.1/tcp/0".parse().expect("valid address; qed");
839	network_config.listen_addresses.push(addr.clone());
840	network_config.transport =
841		TransportConfig::Normal { enable_mdns: false, allow_private_ip: true };
842
843	Ok(Configuration {
844		impl_name: "cumulus-test-node".to_string(),
845		impl_version: "0.1".to_string(),
846		role,
847		tokio_handle,
848		transaction_pool: Default::default(),
849		network: network_config,
850		keystore: KeystoreConfig::InMemory,
851		database: DatabaseSource::RocksDb { path: root.join("db"), cache_size: 128 },
852		trie_cache_maximum_size: Some(64 * 1024 * 1024),
853		warm_up_trie_cache: None,
854		state_pruning: Some(PruningMode::ArchiveAll),
855		blocks_pruning: BlocksPruning::KeepAll,
856		chain_spec: spec,
857		executor: ExecutorConfiguration {
858			wasm_method: WasmExecutionMethod::Compiled {
859				instantiation_strategy:
860					sc_executor_wasmtime::InstantiationStrategy::PoolingCopyOnWrite,
861			},
862			..ExecutorConfiguration::default()
863		},
864		rpc: RpcConfiguration {
865			addr: None,
866			max_connections: Default::default(),
867			cors: None,
868			methods: Default::default(),
869			max_request_size: Default::default(),
870			max_response_size: Default::default(),
871			id_provider: None,
872			max_subs_per_conn: Default::default(),
873			port: 9945,
874			message_buffer_capacity: Default::default(),
875			batch_config: RpcBatchRequestConfig::Unlimited,
876			rate_limit: None,
877			rate_limit_whitelisted_ips: Default::default(),
878			rate_limit_trust_proxy_headers: Default::default(),
879			request_logger_limit: 1024,
880		},
881		prometheus_config: None,
882		telemetry_endpoints: None,
883		offchain_worker: OffchainWorkerConfig { enabled: true, indexing_enabled: false },
884		force_authoring: false,
885		disable_grandpa: false,
886		dev_key_seed: Some(key_seed),
887		tracing_targets: None,
888		tracing_receiver: Default::default(),
889		announce_block: true,
890		data_path: root,
891		base_path,
892		wasm_runtime_overrides: None,
893	})
894}
895
896impl TestNode {
897	/// Wait for `count` blocks to be imported in the node and then exit. This function will not
898	/// return if no blocks are ever created, thus you should restrict the maximum amount of time of
899	/// the test execution.
900	pub fn wait_for_blocks(&self, count: usize) -> impl Future<Output = ()> {
901		self.client.wait_for_blocks(count)
902	}
903
904	/// Send an extrinsic to this node.
905	pub async fn send_extrinsic(
906		&self,
907		function: impl Into<runtime::RuntimeCall>,
908		caller: Sr25519Keyring,
909	) -> Result<RpcTransactionOutput, RpcTransactionError> {
910		let extrinsic = construct_extrinsic(&self.client, function, caller.pair(), Some(0));
911
912		self.rpc_handlers.send_transaction(extrinsic.into()).await
913	}
914
915	/// Register a parachain at this relay chain.
916	pub async fn schedule_upgrade(&self, validation: Vec<u8>) -> Result<(), RpcTransactionError> {
917		let call = frame_system::Call::set_code { code: validation };
918
919		self.send_extrinsic(
920			runtime::SudoCall::sudo_unchecked_weight {
921				call: Box::new(call.into()),
922				weight: Weight::from_parts(1_000, 0),
923			},
924			Sr25519Keyring::Alice,
925		)
926		.await
927		.map(drop)
928	}
929}
930
931/// Fetch account nonce for key pair
932pub fn fetch_nonce(client: &Client, account: sp_core::sr25519::Public) -> u32 {
933	let best_hash = client.chain_info().best_hash;
934	client
935		.runtime_api()
936		.account_nonce(best_hash, account.into())
937		.expect("Fetching account nonce works; qed")
938}
939
940/// Construct an extrinsic that can be applied to the test runtime.
941pub fn construct_extrinsic(
942	client: &Client,
943	function: impl Into<runtime::RuntimeCall>,
944	caller: sp_core::sr25519::Pair,
945	nonce: Option<u32>,
946) -> runtime::UncheckedExtrinsic {
947	let function = function.into();
948	let current_block_hash = client.info().best_hash;
949	let current_block = client.info().best_number.saturated_into();
950	let genesis_block = client.hash(0).unwrap().unwrap();
951	let nonce = nonce.unwrap_or_else(|| fetch_nonce(client, caller.public()));
952	let period = runtime::BlockHashCount::get()
953		.checked_next_power_of_two()
954		.map(|c| c / 2)
955		.unwrap_or(2) as u64;
956	let tip = 0;
957	let tx_ext: runtime::TxExtension = cumulus_pallet_weight_reclaim::StorageWeightReclaim::from((
958		frame_system::AuthorizeCall::<runtime::Runtime>::new(),
959		frame_system::CheckNonZeroSender::<runtime::Runtime>::new(),
960		frame_system::CheckSpecVersion::<runtime::Runtime>::new(),
961		frame_system::CheckGenesis::<runtime::Runtime>::new(),
962		frame_system::CheckEra::<runtime::Runtime>::from(generic::Era::mortal(
963			period,
964			current_block,
965		)),
966		frame_system::CheckNonce::<runtime::Runtime>::from(nonce),
967		frame_system::CheckWeight::<runtime::Runtime>::new(),
968		pallet_transaction_payment::ChargeTransactionPayment::<runtime::Runtime>::from(tip),
969		runtime::TestTransactionExtension::<runtime::Runtime>::default(),
970	))
971	.into();
972	let raw_payload = runtime::SignedPayload::from_raw(
973		function.clone(),
974		tx_ext.clone(),
975		((), (), runtime::VERSION.spec_version, genesis_block, current_block_hash, (), (), (), ()),
976	);
977	let signature = raw_payload.using_encoded(|e| caller.sign(e));
978	runtime::UncheckedExtrinsic::new_signed(
979		function,
980		MultiAddress::Id(caller.public().into()),
981		runtime::Signature::Sr25519(signature),
982		tx_ext,
983	)
984}
985
986/// Run a relay-chain validator node.
987///
988/// This is essentially a wrapper around
989/// [`run_validator_node`](polkadot_test_service::run_validator_node).
990pub fn run_relay_chain_validator_node(
991	tokio_handle: tokio::runtime::Handle,
992	key: Sr25519Keyring,
993	storage_update_func: impl Fn(),
994	boot_nodes: Vec<MultiaddrWithPeerId>,
995	port: Option<u16>,
996) -> polkadot_test_service::PolkadotTestNode {
997	let mut config = polkadot_test_service::node_config(
998		storage_update_func,
999		tokio_handle.clone(),
1000		key,
1001		boot_nodes,
1002		true,
1003	);
1004
1005	if let Some(port) = port {
1006		config.rpc.addr = Some(vec![RpcEndpoint {
1007			batch_config: config.rpc.batch_config,
1008			cors: config.rpc.cors.clone(),
1009			listen_addr: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port)),
1010			max_connections: config.rpc.max_connections,
1011			max_payload_in_mb: config.rpc.max_request_size,
1012			max_payload_out_mb: config.rpc.max_response_size,
1013			max_subscriptions_per_connection: config.rpc.max_subs_per_conn,
1014			max_buffer_capacity_per_connection: config.rpc.message_buffer_capacity,
1015			rpc_methods: config.rpc.methods,
1016			rate_limit: config.rpc.rate_limit,
1017			rate_limit_trust_proxy_headers: config.rpc.rate_limit_trust_proxy_headers,
1018			rate_limit_whitelisted_ips: config.rpc.rate_limit_whitelisted_ips.clone(),
1019			retry_random_port: true,
1020			is_optional: false,
1021		}]);
1022	}
1023
1024	let mut workers_path = std::env::current_exe().unwrap();
1025	workers_path.pop();
1026	workers_path.pop();
1027
1028	tokio_handle.block_on(async move {
1029		polkadot_test_service::run_validator_node(config, Some(workers_path)).await
1030	})
1031}