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