referrerpolicy=no-referrer-when-downgrade

cumulus_test_service/
lib.rs

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