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