lib.rs 13.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.

//! Polkadot test service only.

#![warn(missing_docs)]

21
pub mod chain_spec;
22
23
24

pub use chain_spec::*;
use futures::future::Future;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
25
26
use polkadot_node_primitives::{CollationGenerationConfig, CollatorFn};
use polkadot_node_subsystem::messages::{CollationGenerationMessage, CollatorProtocolMessage};
27
use polkadot_overseer::Handle;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
28
use polkadot_primitives::v1::{Balance, CollatorPair, HeadData, Id as ParaId, ValidationCode};
29
use polkadot_runtime_common::BlockHashCount;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
30
31
use polkadot_runtime_parachains::paras::ParaGenesisArgs;
use polkadot_service::{ClientHandle, Error, ExecuteWithClient, FullClient, IsCollator, NewFull};
32
use polkadot_test_runtime::{
Shawn Tabrizi's avatar
Shawn Tabrizi committed
33
34
	ParasSudoWrapperCall, Runtime, SignedExtra, SignedPayload, SudoCall, UncheckedExtrinsic,
	VERSION,
35
};
36
use sc_chain_spec::ChainSpec;
37
use sc_client_api::execution_extensions::ExecutionStrategies;
38
39
use sc_network::{
	config::{NetworkConfiguration, TransportConfig},
40
	multiaddr,
41
42
};
use service::{
43
	config::{DatabaseSource, KeystoreConfig, MultiaddrWithPeerId, WasmExecutionMethod},
Shawn Tabrizi's avatar
Shawn Tabrizi committed
44
45
	BasePath, Configuration, KeepBlocks, Role, RpcHandlers, TaskExecutor, TaskManager,
	TransactionStorageMode,
46
47
48
49
};
use sp_arithmetic::traits::SaturatedConversion;
use sp_blockchain::HeaderBackend;
use sp_keyring::Sr25519Keyring;
50
use sp_runtime::{codec::Encode, generic, traits::IdentifyAccount, MultiSigner};
51
use sp_state_machine::BasicExternalities;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
52
53
54
55
use std::{path::PathBuf, sync::Arc};
use substrate_test_client::{
	BlockchainEventsExt, RpcHandlersExt, RpcTransactionError, RpcTransactionOutput,
};
56

57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/// Declare an instance of the native executor named `PolkadotTestExecutor`. Include the wasm binary as the
/// equivalent wasm code.
pub struct PolkadotTestExecutor;

impl sc_executor::NativeExecutionDispatch for PolkadotTestExecutor {
	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;

	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {
		polkadot_test_runtime::api::dispatch(method, data)
	}

	fn native_version() -> sc_executor::NativeVersion {
		polkadot_test_runtime::native_version()
	}
}
72

73
74
75
76
77
/// The client type being used by the test service.
pub type Client = FullClient<polkadot_test_runtime::RuntimeApi, PolkadotTestExecutor>;

pub use polkadot_service::FullBackend;

78
/// Create a new full node.
79
#[sc_tracing::logging::prefix_logs_with(config.network.node_name.as_str())]
80
pub fn new_full(
81
	config: Configuration,
82
	is_collator: IsCollator,
83
	worker_program_path: Option<PathBuf>,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
84
) -> Result<NewFull<Arc<Client>>, Error> {
85
	polkadot_service::new_full::<polkadot_test_runtime::RuntimeApi, PolkadotTestExecutor, _>(
86
		config,
87
		is_collator,
88
		None,
89
		true,
90
		None,
91
		None,
92
		worker_program_path,
93
		polkadot_service::RealOverseerGen,
94
	)
95
96
}

97
/// A wrapper for the test client that implements `ClientHandle`.
98
pub struct TestClient(pub Arc<Client>);
99
100
101
102
103
104
105

impl ClientHandle for TestClient {
	fn execute_with<T: ExecuteWithClient>(&self, t: T) -> T::Output {
		T::execute_with_client::<_, _, polkadot_service::FullBackend>(t, self.0.clone())
	}
}

106
107
108
109
110
111
/// Create a Polkadot `Configuration`.
///
/// By default an in-memory socket will be used, therefore you need to provide boot
/// nodes if you want the future node to be connected to other nodes.
///
/// The `storage_update_func` function will be executed in an externalities provided environment
Bernhard Schuster's avatar
Bernhard Schuster committed
112
/// and can be used to make adjustments to the runtime genesis storage.
113
114
115
116
117
pub fn node_config(
	storage_update_func: impl Fn(),
	task_executor: TaskExecutor,
	key: Sr25519Keyring,
	boot_nodes: Vec<MultiaddrWithPeerId>,
118
	is_validator: bool,
119
120
121
) -> Configuration {
	let base_path = BasePath::new_temp_dir().expect("could not create temporary directory");
	let root = base_path.path();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
122
	let role = if is_validator { Role::Authority } else { Role::Full };
123
124
	let key_seed = key.to_seed();
	let mut spec = polkadot_local_testnet_config();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
125
	let mut storage = spec.as_storage_builder().build_storage().expect("could not build storage");
126
127
128
129
130

	BasicExternalities::execute_with_storage(&mut storage, storage_update_func);
	spec.set_storage(storage);

	let mut network_config = NetworkConfiguration::new(
131
		key_seed.to_string(),
132
133
134
135
136
137
138
139
140
		"network/test/0.1",
		Default::default(),
		None,
	);

	network_config.boot_nodes = boot_nodes;

	network_config.allow_non_globals_in_dht = true;

141
	let addr: multiaddr::Multiaddr = multiaddr::Protocol::Memory(rand::random()).into();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
142
	network_config.listen_addresses.push(addr.clone());
143

Shawn Tabrizi's avatar
Shawn Tabrizi committed
144
	network_config.public_addresses.push(addr);
145
146
147
148
149
150
151
152
153
154

	network_config.transport = TransportConfig::MemoryOnly;

	Configuration {
		impl_name: "polkadot-test-node".to_string(),
		impl_version: "0.1".to_string(),
		role,
		task_executor,
		transaction_pool: Default::default(),
		network: network_config,
155
		keystore: KeystoreConfig::InMemory,
156
		keystore_remote: Default::default(),
157
		database: DatabaseSource::RocksDb { path: root.join("db"), cache_size: 128 },
158
159
		state_cache_size: 16777216,
		state_cache_child_ratio: None,
160
161
162
		state_pruning: Default::default(),
		keep_blocks: KeepBlocks::All,
		transaction_storage: TransactionStorageMode::BlockBody,
163
164
		chain_spec: Box::new(spec),
		wasm_method: WasmExecutionMethod::Interpreted,
165
		wasm_runtime_overrides: Default::default(),
166
167
168
169
170
171
172
173
		// NOTE: we enforce the use of the native runtime to make the errors more debuggable
		execution_strategies: ExecutionStrategies {
			syncing: sc_client_api::ExecutionStrategy::NativeWhenPossible,
			importing: sc_client_api::ExecutionStrategy::NativeWhenPossible,
			block_construction: sc_client_api::ExecutionStrategy::NativeWhenPossible,
			offchain_worker: sc_client_api::ExecutionStrategy::NativeWhenPossible,
			other: sc_client_api::ExecutionStrategy::NativeWhenPossible,
		},
Niklas Adolfsson's avatar
Niklas Adolfsson committed
174
		rpc_http_threads: None,
175
176
177
		rpc_http: None,
		rpc_ws: None,
		rpc_ipc: None,
178
		rpc_max_payload: None,
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
		rpc_ws_max_connections: None,
		rpc_cors: None,
		rpc_methods: Default::default(),
		prometheus_config: None,
		telemetry_endpoints: None,
		telemetry_external_transport: None,
		default_heap_pages: None,
		offchain_worker: Default::default(),
		force_authoring: false,
		disable_grandpa: false,
		dev_key_seed: Some(key_seed),
		tracing_targets: None,
		tracing_receiver: Default::default(),
		max_runtime_instances: 8,
		announce_block: true,
		base_path: Some(base_path),
195
		informant_output_format: Default::default(),
196
		disable_log_reloading: false,
197
198
199
200
201
202
203
204
205
	}
}

/// Run a test validator node that uses the test runtime.
///
/// The node will be using an in-memory socket, therefore you need to provide boot nodes if you
/// want it to be connected to other nodes.
///
/// The `storage_update_func` function will be executed in an externalities provided environment
Bernhard Schuster's avatar
Bernhard Schuster committed
206
/// and can be used to make adjustments to the runtime genesis storage.
207
208
209
210
211
pub fn run_validator_node(
	task_executor: TaskExecutor,
	key: Sr25519Keyring,
	storage_update_func: impl Fn(),
	boot_nodes: Vec<MultiaddrWithPeerId>,
212
	worker_program_path: Option<PathBuf>,
213
214
215
) -> PolkadotTestNode {
	let config = node_config(storage_update_func, task_executor, key, boot_nodes, true);
	let multiaddr = config.network.listen_addresses[0].clone();
Andronik Ordian's avatar
Andronik Ordian committed
216
	let NewFull { task_manager, client, network, rpc_handlers, overseer_handle, .. } =
Shawn Tabrizi's avatar
Shawn Tabrizi committed
217
218
		new_full(config, IsCollator::No, worker_program_path)
			.expect("could not create Polkadot test service");
219

Andronik Ordian's avatar
Andronik Ordian committed
220
	let overseer_handle = overseer_handle.expect("test node must have an overseer handle");
221
222
223
	let peer_id = network.local_peer_id().clone();
	let addr = MultiaddrWithPeerId { multiaddr, peer_id };

Shawn Tabrizi's avatar
Shawn Tabrizi committed
224
	PolkadotTestNode { task_manager, client, overseer_handle, addr, rpc_handlers }
225
226
}

227
/// Run a test collator node that uses the test runtime.
228
229
230
231
232
///
/// The node will be using an in-memory socket, therefore you need to provide boot nodes if you
/// want it to be connected to other nodes.
///
/// The `storage_update_func` function will be executed in an externalities provided environment
Bernhard Schuster's avatar
Bernhard Schuster committed
233
/// and can be used to make adjustments to the runtime genesis storage.
234
235
236
///
/// # Note
///
Bernhard Schuster's avatar
Bernhard Schuster committed
237
/// The collator functionality still needs to be registered at the node! This can be done using
238
239
/// [`PolkadotTestNode::register_collator`].
pub fn run_collator_node(
240
241
242
243
	task_executor: TaskExecutor,
	key: Sr25519Keyring,
	storage_update_func: impl Fn(),
	boot_nodes: Vec<MultiaddrWithPeerId>,
244
	collator_pair: CollatorPair,
245
) -> PolkadotTestNode {
246
	let config = node_config(storage_update_func, task_executor, key, boot_nodes, false);
247
	let multiaddr = config.network.listen_addresses[0].clone();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
248
249
250
	let NewFull { task_manager, client, network, rpc_handlers, overseer_handle, .. } =
		new_full(config, IsCollator::Yes(collator_pair), None)
			.expect("could not create Polkadot test service");
251

Andronik Ordian's avatar
Andronik Ordian committed
252
	let overseer_handle = overseer_handle.expect("test node must have an overseer handle");
253
254
255
	let peer_id = network.local_peer_id().clone();
	let addr = MultiaddrWithPeerId { multiaddr, peer_id };

Shawn Tabrizi's avatar
Shawn Tabrizi committed
256
	PolkadotTestNode { task_manager, client, overseer_handle, addr, rpc_handlers }
257
258
259
}

/// A Polkadot test node instance used for testing.
260
pub struct PolkadotTestNode {
Denis_P's avatar
Denis_P committed
261
	/// `TaskManager`'s instance.
262
	pub task_manager: TaskManager,
263
	/// Client's instance.
264
	pub client: Arc<Client>,
Andronik Ordian's avatar
Andronik Ordian committed
265
266
	/// A handle to Overseer.
	pub overseer_handle: Handle,
267
268
	/// The `MultiaddrWithPeerId` to this node. This is useful if you want to pass it as "boot node" to other nodes.
	pub addr: MultiaddrWithPeerId,
Denis_P's avatar
Denis_P committed
269
	/// `RPCHandlers` to make RPC queries.
Seun Lanlege's avatar
Seun Lanlege committed
270
	pub rpc_handlers: RpcHandlers,
271
272
}

273
274
275
impl PolkadotTestNode {
	/// Send an extrinsic to this node.
	pub async fn send_extrinsic(
276
		&self,
277
		function: impl Into<polkadot_test_runtime::Call>,
278
279
		caller: Sr25519Keyring,
	) -> Result<RpcTransactionOutput, RpcTransactionError> {
280
		let extrinsic = construct_extrinsic(&*self.client, function, caller);
281
282
283

		self.rpc_handlers.send_transaction(extrinsic.into()).await
	}
284
285
286
287
288

	/// Register a parachain at this relay chain.
	pub async fn register_parachain(
		&self,
		id: ParaId,
289
290
		validation_code: impl Into<ValidationCode>,
		genesis_head: impl Into<HeadData>,
291
292
293
294
	) -> Result<(), RpcTransactionError> {
		let call = ParasSudoWrapperCall::sudo_schedule_para_initialize(
			id,
			ParaGenesisArgs {
295
296
				genesis_head: genesis_head.into(),
				validation_code: validation_code.into(),
297
298
299
300
				parachain: true,
			},
		);

Shawn Tabrizi's avatar
Shawn Tabrizi committed
301
302
303
		self.send_extrinsic(SudoCall::sudo(Box::new(call.into())), Sr25519Keyring::Alice)
			.await
			.map(drop)
304
	}
305
306
307
308
309
310

	/// Wait for `count` blocks to be imported in the node and then exit. This function will not return if no blocks
	/// are ever created, thus you should restrict the maximum amount of time of the test execution.
	pub fn wait_for_blocks(&self, count: usize) -> impl Future<Output = ()> {
		self.client.wait_for_blocks(count)
	}
311
312
313
314
315
316

	/// Register the collator functionality in the overseer of this node.
	pub async fn register_collator(
		&mut self,
		collator_key: CollatorPair,
		para_id: ParaId,
Sergey Pepyakin's avatar
Sergey Pepyakin committed
317
		collator: CollatorFn,
318
	) {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
319
		let config = CollationGenerationConfig { key: collator_key, collator, para_id };
320

Andronik Ordian's avatar
Andronik Ordian committed
321
		self.overseer_handle
322
			.send_msg(CollationGenerationMessage::Initialize(config), "Collator")
323
			.await;
324

Andronik Ordian's avatar
Andronik Ordian committed
325
		self.overseer_handle
326
			.send_msg(CollatorProtocolMessage::CollateOn(para_id), "Collator")
327
			.await;
328
	}
329
}
330
331
332
333
334
335
336
337
338
339
340
341

/// Construct an extrinsic that can be applied to the test runtime.
pub fn construct_extrinsic(
	client: &Client,
	function: impl Into<polkadot_test_runtime::Call>,
	caller: Sr25519Keyring,
) -> UncheckedExtrinsic {
	let function = function.into();
	let current_block_hash = client.info().best_hash;
	let current_block = client.info().best_number.saturated_into();
	let genesis_block = client.hash(0).unwrap().unwrap();
	let nonce = 0;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
342
343
	let period =
		BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2) as u64;
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
	let tip = 0;
	let extra: SignedExtra = (
		frame_system::CheckSpecVersion::<Runtime>::new(),
		frame_system::CheckTxVersion::<Runtime>::new(),
		frame_system::CheckGenesis::<Runtime>::new(),
		frame_system::CheckEra::<Runtime>::from(generic::Era::mortal(period, current_block)),
		frame_system::CheckNonce::<Runtime>::from(nonce),
		frame_system::CheckWeight::<Runtime>::new(),
		pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
	);
	let raw_payload = SignedPayload::from_raw(
		function.clone(),
		extra.clone(),
		(
			VERSION.spec_version,
			VERSION.transaction_version,
			genesis_block,
			current_block_hash,
			(),
			(),
			(),
		),
	);
	let signature = raw_payload.using_encoded(|e| caller.sign(e));
	UncheckedExtrinsic::new_signed(
		function.clone(),
		polkadot_test_runtime::Address::Id(caller.public().into()),
		polkadot_primitives::v0::Signature::Sr25519(signature.clone()),
		extra.clone(),
	)
}

/// Construct a transfer extrinsic.
pub fn construct_transfer_extrinsic(
	client: &Client,
	origin: sp_keyring::AccountKeyring,
	dest: sp_keyring::AccountKeyring,
	value: Balance,
) -> UncheckedExtrinsic {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
383
384
385
386
	let function = polkadot_test_runtime::Call::Balances(pallet_balances::Call::transfer(
		MultiSigner::from(dest.public()).into_account().into(),
		value,
	));
387
388
389

	construct_extrinsic(client, function, origin)
}