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		})
378		.await?;
379
380	let keystore = params.keystore_container.keystore();
381
382	if collator_key.is_some() && collator_reserved_slots > 0 {
383		cumulus_client_collator_discovery::start_collator_discovery(
384			cumulus_client_collator_discovery::StartCollatorDiscoveryParams {
385				max_reserved: collator_reserved_slots,
386				client: client.clone(),
387				authority_discovery: client.clone(),
388				network: network.clone(),
389				sync_service: sync_service.clone(),
390				network_event_stream: network.event_stream("para-authority-discovery"),
391				keystore: keystore.clone(),
392				genesis_hash: client.chain_info().genesis_hash,
393				fork_id: parachain_config.chain_spec.fork_id().map(ToString::to_string),
394				publish_non_global_ips: parachain_config.network.allow_non_globals_in_dht,
395				public_addresses: parachain_config.network.public_addresses.clone(),
396				persisted_cache_directory: parachain_config.network.net_config_path.clone(),
397				prometheus_registry: prometheus_registry.clone(),
398				spawn_handle: task_manager.spawn_handle(),
399			},
400		)
401		.map_err(|e| sc_service::Error::Application(Box::new(e)))?;
402	}
403
404	let rpc_builder = {
405		let client = client.clone();
406		Box::new(move |_| rpc_ext_builder(client.clone()))
407	};
408
409	let rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
410		rpc_builder,
411		client: client.clone(),
412		transaction_pool: transaction_pool.clone(),
413		task_manager: &mut task_manager,
414		config: parachain_config,
415		keystore: keystore.clone(),
416		backend: backend.clone(),
417		network: network.clone(),
418		sync_service: sync_service.clone(),
419		system_rpc_tx,
420		tx_handler_controller,
421		telemetry: None,
422		tracing_execute_block: Some(Arc::new(ParachainTracingExecuteBlock::new(client.clone()))),
423	})?;
424
425	let announce_block = {
426		let sync_service = sync_service.clone();
427		Arc::new(move |hash, data| sync_service.announce_block(hash, data))
428	};
429
430	let announce_block = wrap_announce_block
431		.map(|w| (w)(announce_block.clone()))
432		.unwrap_or_else(|| announce_block);
433
434	let overseer_handle = relay_chain_interface
435		.overseer_handle()
436		.map_err(|e| sc_service::Error::Application(Box::new(e)))?;
437
438	let recovery_handle: Box<dyn RecoveryHandle> = if fail_pov_recovery {
439		Box::new(FailingRecoveryHandle::new(overseer_handle.clone()))
440	} else {
441		Box::new(overseer_handle.clone())
442	};
443	let relay_chain_slot_duration = Duration::from_secs(6);
444
445	start_relay_chain_tasks(StartRelayChainTasksParams {
446		client: client.clone(),
447		announce_block: announce_block.clone(),
448		para_id,
449		relay_chain_interface: relay_chain_interface.clone(),
450		task_manager: &mut task_manager,
451		// Increase speed of recovery for testing purposes.
452		da_recovery_profile: DARecoveryProfile::Other(RecoveryDelayRange {
453			min: Duration::from_secs(1),
454			max: Duration::from_secs(5),
455		}),
456		import_queue: import_queue_service,
457		relay_chain_slot_duration,
458		recovery_handle,
459		sync_service: sync_service.clone(),
460		prometheus_registry: None,
461	})?;
462
463	let collator_peer_id = relay_chain_peer_id;
464	if let Some(collator_key) = collator_key {
465		let proposer = sc_basic_authorship::ProposerFactory::new(
466			task_manager.spawn_handle(),
467			client.clone(),
468			transaction_pool.clone(),
469			prometheus_registry.as_ref(),
470			None,
471		);
472
473		let collator_service = CollatorService::new(client.clone(), announce_block, client.clone());
474
475		let client_for_aura = client.clone();
476
477		if use_slot_based_collator {
478			tracing::info!(target: LOG_TARGET, "Starting block authoring with slot based authoring.");
479			let params = SlotBasedParams {
480				create_inherent_data_providers: move |_, ()| async move { Ok(()) },
481				block_import,
482				para_client: client.clone(),
483				para_backend: backend.clone(),
484				relay_client: relay_chain_interface,
485				code_hash_provider: move |block_hash| {
486					client_for_aura.code_at(block_hash).ok().map(|c| ValidationCode::from(c).hash())
487				},
488				keystore,
489				collator_key,
490				relay_chain_slot_duration,
491				para_id,
492				proposer,
493				collator_service,
494				reinitialize: false,
495				slot_offset: Duration::from_secs(1),
496				block_import_handle,
497				spawner: task_manager.spawn_essential_handle(),
498				export_pov: None,
499				max_pov_percentage: None,
500				collator_peer_id,
501			};
502
503			slot_based::run::<Block, AuthorityPair, _, _, _, _, _, _, _, _, _>(params);
504		} else {
505			tracing::info!(target: LOG_TARGET, "Starting block authoring with lookahead collator.");
506			let params = AuraParams {
507				create_inherent_data_providers: move |_, ()| async move { Ok(()) },
508				block_import,
509				para_client: client.clone(),
510				para_backend: backend.clone(),
511				relay_client: relay_chain_interface,
512				code_hash_provider: move |block_hash| {
513					client_for_aura.code_at(block_hash).ok().map(|c| ValidationCode::from(c).hash())
514				},
515				keystore,
516				collator_key,
517				collator_peer_id,
518				para_id,
519				overseer_handle,
520				relay_chain_slot_duration,
521				proposer,
522				collator_service,
523				authoring_duration: Duration::from_millis(2000),
524				reinitialize: false,
525				max_pov_percentage: None,
526			};
527
528			let fut = aura::run::<Block, AuthorityPair, _, _, _, _, _, _, _, _>(params);
529			task_manager.spawn_essential_handle().spawn("aura", None, fut);
530		}
531	}
532
533	Ok((task_manager, client, network, rpc_handlers, transaction_pool, backend))
534}
535
536/// A Cumulus test node instance used for testing.
537pub struct TestNode {
538	/// TaskManager's instance.
539	pub task_manager: TaskManager,
540	/// Client's instance.
541	pub client: Arc<Client>,
542	/// Node's network.
543	pub network: Arc<dyn NetworkService>,
544	/// The `MultiaddrWithPeerId` to this node. This is useful if you want to pass it as "boot
545	/// node" to other nodes.
546	pub addr: MultiaddrWithPeerId,
547	/// RPCHandlers to make RPC queries.
548	pub rpc_handlers: RpcHandlers,
549	/// Node's transaction pool
550	pub transaction_pool: TransactionPool,
551	/// Node's backend
552	pub backend: Arc<Backend>,
553}
554
555/// A builder to create a [`TestNode`].
556pub struct TestNodeBuilder {
557	para_id: ParaId,
558	tokio_handle: tokio::runtime::Handle,
559	key: Sr25519Keyring,
560	collator_key: Option<CollatorPair>,
561	parachain_nodes: Vec<MultiaddrWithPeerId>,
562	parachain_nodes_exclusive: bool,
563	relay_chain_nodes: Vec<MultiaddrWithPeerId>,
564	wrap_announce_block: Option<Box<dyn FnOnce(AnnounceBlockFn) -> AnnounceBlockFn>>,
565	storage_update_func_parachain: Option<Box<dyn Fn()>>,
566	storage_update_func_relay_chain: Option<Box<dyn Fn()>>,
567	relay_chain_mode: RelayChainMode,
568	endowed_accounts: Vec<AccountId>,
569	record_proof_during_import: bool,
570}
571
572impl TestNodeBuilder {
573	/// Create a new instance of `Self`.
574	///
575	/// `para_id` - The parachain id this node is running for.
576	/// `tokio_handle` - The tokio handler to use.
577	/// `key` - The key that will be used to generate the name and that will be passed as
578	/// `dev_seed`.
579	pub fn new(para_id: ParaId, tokio_handle: tokio::runtime::Handle, key: Sr25519Keyring) -> Self {
580		TestNodeBuilder {
581			key,
582			para_id,
583			tokio_handle,
584			collator_key: None,
585			parachain_nodes: Vec::new(),
586			parachain_nodes_exclusive: false,
587			relay_chain_nodes: Vec::new(),
588			wrap_announce_block: None,
589			storage_update_func_parachain: None,
590			storage_update_func_relay_chain: None,
591			endowed_accounts: Default::default(),
592			relay_chain_mode: RelayChainMode::Embedded,
593			record_proof_during_import: true,
594		}
595	}
596
597	/// Enable collator for this node.
598	pub fn enable_collator(mut self) -> Self {
599		let collator_key = CollatorPair::generate().0;
600		self.collator_key = Some(collator_key);
601		self
602	}
603
604	/// Instruct the node to exclusively connect to registered parachain nodes.
605	///
606	/// Parachain nodes can be registered using [`Self::connect_to_parachain_node`] and
607	/// [`Self::connect_to_parachain_nodes`].
608	pub fn exclusively_connect_to_registered_parachain_nodes(mut self) -> Self {
609		self.parachain_nodes_exclusive = true;
610		self
611	}
612
613	/// Make the node connect to the given parachain node.
614	///
615	/// By default the node will not be connected to any node or will be able to discover any other
616	/// node.
617	pub fn connect_to_parachain_node(mut self, node: &TestNode) -> Self {
618		self.parachain_nodes.push(node.addr.clone());
619		self
620	}
621
622	/// Make the node connect to the given parachain nodes.
623	///
624	/// By default the node will not be connected to any node or will be able to discover any other
625	/// node.
626	pub fn connect_to_parachain_nodes<'a>(
627		mut self,
628		nodes: impl IntoIterator<Item = &'a TestNode>,
629	) -> Self {
630		self.parachain_nodes.extend(nodes.into_iter().map(|n| n.addr.clone()));
631		self
632	}
633
634	/// Make the node connect to the given relay chain node.
635	///
636	/// By default the node will not be connected to any node or will be able to discover any other
637	/// node.
638	pub fn connect_to_relay_chain_node(
639		mut self,
640		node: &polkadot_test_service::PolkadotTestNode,
641	) -> Self {
642		self.relay_chain_nodes.push(node.addr.clone());
643		self
644	}
645
646	/// Make the node connect to the given relay chain nodes.
647	///
648	/// By default the node will not be connected to any node or will be able to discover any other
649	/// node.
650	pub fn connect_to_relay_chain_nodes<'a>(
651		mut self,
652		nodes: impl IntoIterator<Item = &'a polkadot_test_service::PolkadotTestNode>,
653	) -> Self {
654		self.relay_chain_nodes.extend(nodes.into_iter().map(|n| n.addr.clone()));
655		self
656	}
657
658	/// Wrap the announce block function of this node.
659	pub fn wrap_announce_block(
660		mut self,
661		wrap: impl FnOnce(AnnounceBlockFn) -> AnnounceBlockFn + 'static,
662	) -> Self {
663		self.wrap_announce_block = Some(Box::new(wrap));
664		self
665	}
666
667	/// Allows accessing the parachain storage before the test node is built.
668	pub fn update_storage_parachain(mut self, updater: impl Fn() + 'static) -> Self {
669		self.storage_update_func_parachain = Some(Box::new(updater));
670		self
671	}
672
673	/// Allows accessing the relay chain storage before the test node is built.
674	pub fn update_storage_relay_chain(mut self, updater: impl Fn() + 'static) -> Self {
675		self.storage_update_func_relay_chain = Some(Box::new(updater));
676		self
677	}
678
679	/// Connect to full node via RPC.
680	pub fn use_external_relay_chain_node_at_url(mut self, network_address: Url) -> Self {
681		self.relay_chain_mode = RelayChainMode::ExternalRpc(vec![network_address]);
682		self
683	}
684
685	/// Connect to full node via RPC.
686	pub fn use_external_relay_chain_node_at_port(mut self, port: u16) -> Self {
687		let mut localhost_url =
688			Url::parse("ws://localhost").expect("Should be able to parse localhost Url");
689		localhost_url.set_port(Some(port)).expect("Should be able to set port");
690		self.relay_chain_mode = RelayChainMode::ExternalRpc(vec![localhost_url]);
691		self
692	}
693
694	/// Accounts which will have an initial balance.
695	pub fn endowed_accounts(mut self, accounts: Vec<AccountId>) -> TestNodeBuilder {
696		self.endowed_accounts = accounts;
697		self
698	}
699
700	/// Record proofs during import.
701	pub fn import_proof_recording(mut self, should_record_proof: bool) -> TestNodeBuilder {
702		self.record_proof_during_import = should_record_proof;
703		self
704	}
705
706	/// Build the [`TestNode`].
707	pub async fn build(self) -> TestNode {
708		let parachain_config = node_config(
709			self.storage_update_func_parachain.unwrap_or_else(|| Box::new(|| ())),
710			self.tokio_handle.clone(),
711			self.key,
712			self.parachain_nodes,
713			self.parachain_nodes_exclusive,
714			self.para_id,
715			self.collator_key.is_some(),
716			self.endowed_accounts,
717		)
718		.expect("could not generate Configuration");
719
720		let mut relay_chain_config = polkadot_test_service::node_config(
721			self.storage_update_func_relay_chain.unwrap_or_else(|| Box::new(|| ())),
722			self.tokio_handle,
723			self.key,
724			self.relay_chain_nodes,
725			false,
726		);
727
728		let collator_options = CollatorOptions {
729			relay_chain_mode: self.relay_chain_mode,
730			embedded_dht_bootnode: true,
731			dht_bootnode_discovery: true,
732		};
733
734		relay_chain_config.network.node_name =
735			format!("{} (relay chain)", relay_chain_config.network.node_name);
736
737		let (task_manager, client, network, rpc_handlers, transaction_pool, backend) =
738			match relay_chain_config.network.network_backend {
739				sc_network::config::NetworkBackendType::Libp2p => {
740					start_node_impl::<_, sc_network::NetworkWorker<_, _>>(
741						parachain_config,
742						self.collator_key,
743						relay_chain_config,
744						self.wrap_announce_block,
745						false,
746						|_| Ok(jsonrpsee::RpcModule::new(())),
747						collator_options,
748						self.record_proof_during_import,
749						false,
750						0,
751					)
752					.await
753					.expect("could not create Cumulus test service")
754				},
755				sc_network::config::NetworkBackendType::Litep2p => {
756					start_node_impl::<_, sc_network::Litep2pNetworkBackend>(
757						parachain_config,
758						self.collator_key,
759						relay_chain_config,
760						self.wrap_announce_block,
761						false,
762						|_| Ok(jsonrpsee::RpcModule::new(())),
763						collator_options,
764						self.record_proof_during_import,
765						false,
766						0,
767					)
768					.await
769					.expect("could not create Cumulus test service")
770				},
771			};
772		let peer_id = network.local_peer_id();
773		let multiaddr = polkadot_test_service::get_listen_address(network.clone()).await;
774		let addr = MultiaddrWithPeerId { multiaddr, peer_id };
775
776		TestNode { task_manager, client, network, addr, rpc_handlers, transaction_pool, backend }
777	}
778}
779
780/// Create a Cumulus `Configuration`.
781///
782/// By default a TCP socket will be used, therefore you need to provide nodes if you want the
783/// node to be connected to other nodes.
784///
785/// If `nodes_exclusive` is `true`, the node will only connect to the given `nodes` and not to any
786/// other node.
787///
788/// The `storage_update_func` can be used to make adjustments to the runtime genesis.
789pub fn node_config(
790	storage_update_func: impl Fn(),
791	tokio_handle: tokio::runtime::Handle,
792	key: Sr25519Keyring,
793	nodes: Vec<MultiaddrWithPeerId>,
794	nodes_exclusive: bool,
795	para_id: ParaId,
796	is_collator: bool,
797	endowed_accounts: Vec<AccountId>,
798) -> Result<Configuration, ServiceError> {
799	let base_path = BasePath::new_temp_dir()?;
800	let root = base_path.path().join(format!("cumulus_test_service_{}", key));
801	let role = if is_collator { Role::Authority } else { Role::Full };
802	let key_seed = key.to_seed();
803	let mut spec = Box::new(chain_spec::get_chain_spec_with_extra_endowed(
804		Some(para_id),
805		endowed_accounts,
806		cumulus_test_runtime::WASM_BINARY.expect("WASM binary was not built, please build it!"),
807	));
808
809	let mut storage = spec.as_storage_builder().build_storage().expect("could not build storage");
810
811	BasicExternalities::execute_with_storage(&mut storage, storage_update_func);
812	spec.set_storage(storage);
813
814	let mut network_config = NetworkConfiguration::new(
815		format!("{} (parachain)", key_seed),
816		"network/test/0.1",
817		Default::default(),
818		None,
819	);
820
821	if nodes_exclusive {
822		network_config.default_peers_set.reserved_nodes = nodes;
823		network_config.default_peers_set.non_reserved_mode =
824			sc_network::config::NonReservedPeerMode::Deny;
825	} else {
826		network_config.boot_nodes = nodes;
827	}
828
829	network_config.allow_non_globals_in_dht = true;
830
831	let addr: multiaddr::Multiaddr = "/ip4/127.0.0.1/tcp/0".parse().expect("valid address; qed");
832	network_config.listen_addresses.push(addr.clone());
833	network_config.transport =
834		TransportConfig::Normal { enable_mdns: false, allow_private_ip: true };
835
836	Ok(Configuration {
837		impl_name: "cumulus-test-node".to_string(),
838		impl_version: "0.1".to_string(),
839		role,
840		tokio_handle,
841		transaction_pool: Default::default(),
842		network: network_config,
843		keystore: KeystoreConfig::InMemory,
844		database: DatabaseSource::RocksDb { path: root.join("db"), cache_size: 128 },
845		trie_cache_maximum_size: Some(64 * 1024 * 1024),
846		warm_up_trie_cache: None,
847		state_pruning: Some(PruningMode::ArchiveAll),
848		blocks_pruning: BlocksPruning::KeepAll,
849		chain_spec: spec,
850		executor: ExecutorConfiguration {
851			wasm_method: WasmExecutionMethod::Compiled {
852				instantiation_strategy:
853					sc_executor_wasmtime::InstantiationStrategy::PoolingCopyOnWrite,
854			},
855			..ExecutorConfiguration::default()
856		},
857		rpc: RpcConfiguration {
858			addr: None,
859			max_connections: Default::default(),
860			cors: None,
861			methods: Default::default(),
862			max_request_size: Default::default(),
863			max_response_size: Default::default(),
864			id_provider: None,
865			max_subs_per_conn: Default::default(),
866			port: 9945,
867			message_buffer_capacity: Default::default(),
868			batch_config: RpcBatchRequestConfig::Unlimited,
869			rate_limit: None,
870			rate_limit_whitelisted_ips: Default::default(),
871			rate_limit_trust_proxy_headers: Default::default(),
872			request_logger_limit: 1024,
873		},
874		prometheus_config: None,
875		telemetry_endpoints: None,
876		offchain_worker: OffchainWorkerConfig { enabled: true, indexing_enabled: false },
877		force_authoring: false,
878		disable_grandpa: false,
879		dev_key_seed: Some(key_seed),
880		tracing_targets: None,
881		tracing_receiver: Default::default(),
882		announce_block: true,
883		data_path: root,
884		base_path,
885		wasm_runtime_overrides: None,
886	})
887}
888
889impl TestNode {
890	/// Wait for `count` blocks to be imported in the node and then exit. This function will not
891	/// return if no blocks are ever created, thus you should restrict the maximum amount of time of
892	/// the test execution.
893	pub fn wait_for_blocks(&self, count: usize) -> impl Future<Output = ()> {
894		self.client.wait_for_blocks(count)
895	}
896
897	/// Send an extrinsic to this node.
898	pub async fn send_extrinsic(
899		&self,
900		function: impl Into<runtime::RuntimeCall>,
901		caller: Sr25519Keyring,
902	) -> Result<RpcTransactionOutput, RpcTransactionError> {
903		let extrinsic = construct_extrinsic(&self.client, function, caller.pair(), Some(0));
904
905		self.rpc_handlers.send_transaction(extrinsic.into()).await
906	}
907
908	/// Register a parachain at this relay chain.
909	pub async fn schedule_upgrade(&self, validation: Vec<u8>) -> Result<(), RpcTransactionError> {
910		let call = frame_system::Call::set_code { code: validation };
911
912		self.send_extrinsic(
913			runtime::SudoCall::sudo_unchecked_weight {
914				call: Box::new(call.into()),
915				weight: Weight::from_parts(1_000, 0),
916			},
917			Sr25519Keyring::Alice,
918		)
919		.await
920		.map(drop)
921	}
922}
923
924/// Fetch account nonce for key pair
925pub fn fetch_nonce(client: &Client, account: sp_core::sr25519::Public) -> u32 {
926	let best_hash = client.chain_info().best_hash;
927	client
928		.runtime_api()
929		.account_nonce(best_hash, account.into())
930		.expect("Fetching account nonce works; qed")
931}
932
933/// Construct an extrinsic that can be applied to the test runtime.
934pub fn construct_extrinsic(
935	client: &Client,
936	function: impl Into<runtime::RuntimeCall>,
937	caller: sp_core::sr25519::Pair,
938	nonce: Option<u32>,
939) -> runtime::UncheckedExtrinsic {
940	let function = function.into();
941	let current_block_hash = client.info().best_hash;
942	let current_block = client.info().best_number.saturated_into();
943	let genesis_block = client.hash(0).unwrap().unwrap();
944	let nonce = nonce.unwrap_or_else(|| fetch_nonce(client, caller.public()));
945	let period = runtime::BlockHashCount::get()
946		.checked_next_power_of_two()
947		.map(|c| c / 2)
948		.unwrap_or(2) as u64;
949	let tip = 0;
950	let tx_ext: runtime::TxExtension = cumulus_pallet_weight_reclaim::StorageWeightReclaim::from((
951		frame_system::AuthorizeCall::<runtime::Runtime>::new(),
952		frame_system::CheckNonZeroSender::<runtime::Runtime>::new(),
953		frame_system::CheckSpecVersion::<runtime::Runtime>::new(),
954		frame_system::CheckGenesis::<runtime::Runtime>::new(),
955		frame_system::CheckEra::<runtime::Runtime>::from(generic::Era::mortal(
956			period,
957			current_block,
958		)),
959		frame_system::CheckNonce::<runtime::Runtime>::from(nonce),
960		frame_system::CheckWeight::<runtime::Runtime>::new(),
961		pallet_transaction_payment::ChargeTransactionPayment::<runtime::Runtime>::from(tip),
962		runtime::TestTransactionExtension::<runtime::Runtime>::default(),
963	))
964	.into();
965	let raw_payload = runtime::SignedPayload::from_raw(
966		function.clone(),
967		tx_ext.clone(),
968		((), (), runtime::VERSION.spec_version, genesis_block, current_block_hash, (), (), (), ()),
969	);
970	let signature = raw_payload.using_encoded(|e| caller.sign(e));
971	runtime::UncheckedExtrinsic::new_signed(
972		function,
973		MultiAddress::Id(caller.public().into()),
974		runtime::Signature::Sr25519(signature),
975		tx_ext,
976	)
977}
978
979/// Run a relay-chain validator node.
980///
981/// This is essentially a wrapper around
982/// [`run_validator_node`](polkadot_test_service::run_validator_node).
983pub fn run_relay_chain_validator_node(
984	tokio_handle: tokio::runtime::Handle,
985	key: Sr25519Keyring,
986	storage_update_func: impl Fn(),
987	boot_nodes: Vec<MultiaddrWithPeerId>,
988	port: Option<u16>,
989) -> polkadot_test_service::PolkadotTestNode {
990	let mut config = polkadot_test_service::node_config(
991		storage_update_func,
992		tokio_handle.clone(),
993		key,
994		boot_nodes,
995		true,
996	);
997
998	if let Some(port) = port {
999		config.rpc.addr = Some(vec![RpcEndpoint {
1000			batch_config: config.rpc.batch_config,
1001			cors: config.rpc.cors.clone(),
1002			listen_addr: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port)),
1003			max_connections: config.rpc.max_connections,
1004			max_payload_in_mb: config.rpc.max_request_size,
1005			max_payload_out_mb: config.rpc.max_response_size,
1006			max_subscriptions_per_connection: config.rpc.max_subs_per_conn,
1007			max_buffer_capacity_per_connection: config.rpc.message_buffer_capacity,
1008			rpc_methods: config.rpc.methods,
1009			rate_limit: config.rpc.rate_limit,
1010			rate_limit_trust_proxy_headers: config.rpc.rate_limit_trust_proxy_headers,
1011			rate_limit_whitelisted_ips: config.rpc.rate_limit_whitelisted_ips.clone(),
1012			retry_random_port: true,
1013			is_optional: false,
1014		}]);
1015	}
1016
1017	let mut workers_path = std::env::current_exe().unwrap();
1018	workers_path.pop();
1019	workers_path.pop();
1020
1021	tokio_handle.block_on(async move {
1022		polkadot_test_service::run_validator_node(config, Some(workers_path)).await
1023	})
1024}