mod.rs 10.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Copyright 2018 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/>.

17
//! Tests for polkadot and validation network.
18

19
use super::{PolkadotProtocol, Status, Message, FullStatus};
20
use validation::SessionParams;
21

22
use polkadot_validation::GenericStatement;
23
use polkadot_primitives::{Block, Hash, SessionKey};
24
25
26
27
use polkadot_primitives::parachain::{
	CandidateReceipt, HeadData, PoVBlock, BlockData, CollatorId, ValidatorId,
	ConsolidatedIngressRoots,
};
Gav Wood's avatar
Gav Wood committed
28
use substrate_primitives::crypto::UncheckedInto;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
29
use codec::Encode;
30
use substrate_network::{
31
	Severity, PeerId, PeerInfo, ClientHandle, Context, config::Roles,
32
33
34
	message::Message as SubstrateMessage, specialization::NetworkSpecialization,
	generic_message::Message as GenericMessage
};
35
36
37

use futures::Future;

38
mod validation;
39

40
41
#[derive(Default)]
struct TestContext {
42
43
44
	disabled: Vec<PeerId>,
	disconnected: Vec<PeerId>,
	messages: Vec<(PeerId, SubstrateMessage<Block>)>,
45
46
47
48
49
50
51
}

impl Context<Block> for TestContext {
	fn client(&self) -> &ClientHandle<Block> {
		unimplemented!()
	}

52
	fn report_peer(&mut self, peer: PeerId, reason: Severity) {
53
54
55
56
		match reason {
			Severity::Bad(_) => self.disabled.push(peer),
			_ => self.disconnected.push(peer),
		}
57
58
	}

59
	fn peer_info(&self, _peer: &PeerId) -> Option<PeerInfo<Block>> {
60
61
62
		unimplemented!()
	}

63
	fn send_message(&mut self, who: PeerId, data: SubstrateMessage<Block>) {
Gav Wood's avatar
Gav Wood committed
64
		self.messages.push((who, data))
65
66
67
68
	}
}

impl TestContext {
69
	fn has_message(&self, to: PeerId, message: Message) -> bool {
70
71
		use substrate_network::generic_message::Message as GenericMessage;

72
		let encoded = message.encode();
73
74
75
76
77
78
79
		self.messages.iter().any(|&(ref peer, ref msg)| match msg {
			GenericMessage::ChainSpecific(ref data) => peer == &to && data == &encoded,
			_ => false,
		})
	}
}

80
81
82
83
84
85
86
87

fn make_pov(block_data: Vec<u8>) -> PoVBlock {
	PoVBlock {
		block_data: BlockData(block_data),
		ingress: polkadot_primitives::parachain::ConsolidatedIngress(Vec::new()),
	}
}

88
fn make_status(status: &Status, roles: Roles) -> FullStatus {
89
90
	FullStatus {
		version: 1,
91
		min_supported_version: 1,
92
93
94
95
96
97
98
99
		roles,
		best_number: 0,
		best_hash: Default::default(),
		genesis_hash: Default::default(),
		chain_status: status.encode(),
	}
}

100
101
102
103
104
105
fn make_validation_session(parent_hash: Hash, local_key: SessionKey) -> SessionParams {
	SessionParams {
		local_session_key: Some(local_key),
		parent_hash,
		authorities: Vec::new(),
	}
106
107
}

108
fn on_message(protocol: &mut PolkadotProtocol, ctx: &mut TestContext, from: PeerId, message: Message) {
109
	let encoded = message.encode();
110
	protocol.on_message(ctx, from, &mut Some(GenericMessage::ChainSpecific(encoded)));
111
112
113
114
}

#[test]
fn sends_session_key() {
115
	let mut protocol = PolkadotProtocol::new(None);
116

117
118
	let peer_a = PeerId::random();
	let peer_b = PeerId::random();
119
	let parent_hash = [0; 32].into();
Gav Wood's avatar
Gav Wood committed
120
	let local_key: ValidatorId = [1; 32].unchecked_into();
121

122
	let validator_status = Status { collating_for: None };
Gav Wood's avatar
Gav Wood committed
123
	let collator_status = Status { collating_for: Some(([2; 32].unchecked_into(), 5.into())) };
124
125
126

	{
		let mut ctx = TestContext::default();
127
		protocol.on_connect(&mut ctx, peer_a.clone(), make_status(&validator_status, Roles::AUTHORITY));
128
129
130
131
132
		assert!(ctx.messages.is_empty());
	}

	{
		let mut ctx = TestContext::default();
133
134
		let params = make_validation_session(parent_hash, local_key.clone());
		protocol.new_validation_session(&mut ctx, params);
Gav Wood's avatar
Gav Wood committed
135
		assert!(ctx.has_message(peer_a, Message::SessionKey(local_key.clone())));
136
137
138
139
	}

	{
		let mut ctx = TestContext::default();
140
141
		protocol.on_connect(&mut ctx, peer_b.clone(), make_status(&collator_status, Roles::NONE));
		assert!(ctx.has_message(peer_b.clone(), Message::SessionKey(local_key)));
142
143
144
145
146
	}
}

#[test]
fn fetches_from_those_with_knowledge() {
147
	let mut protocol = PolkadotProtocol::new(None);
148

149
150
	let peer_a = PeerId::random();
	let peer_b = PeerId::random();
151
	let parent_hash = [0; 32].into();
Gav Wood's avatar
Gav Wood committed
152
	let local_key: ValidatorId = [1; 32].unchecked_into();
153
154
155
156
157

	let block_data = BlockData(vec![1, 2, 3, 4]);
	let block_data_hash = block_data.hash();
	let candidate_receipt = CandidateReceipt {
		parachain_index: 5.into(),
Gav Wood's avatar
Gav Wood committed
158
		collator: [255; 32].unchecked_into(),
159
		head_data: HeadData(vec![9, 9, 9]),
Gav Wood's avatar
Gav Wood committed
160
		signature: Default::default(),
161
162
163
164
165
166
167
		balance_uploads: Vec::new(),
		egress_queue_roots: Vec::new(),
		fees: 1_000_000,
		block_data_hash,
	};

	let candidate_hash = candidate_receipt.hash();
Gav Wood's avatar
Gav Wood committed
168
169
	let a_key: ValidatorId = [3; 32].unchecked_into();
	let b_key: ValidatorId = [4; 32].unchecked_into();
170
171
172

	let status = Status { collating_for: None };

173
174
175
	let params = make_validation_session(parent_hash, local_key.clone());
	let session = protocol.new_validation_session(&mut TestContext::default(), params);
	let knowledge = session.knowledge();
176

Gav Wood's avatar
Gav Wood committed
177
	knowledge.lock().note_statement(a_key.clone(), &GenericStatement::Valid(candidate_hash));
178
179
180
181
182
183
184
	let canon_roots = ConsolidatedIngressRoots(Vec::new());
	let recv = protocol.fetch_pov_block(
		&mut TestContext::default(),
		&candidate_receipt,
		parent_hash,
		canon_roots,
	);
185
186
187
188

	// connect peer A
	{
		let mut ctx = TestContext::default();
189
190
		protocol.on_connect(&mut ctx, peer_a.clone(), make_status(&status, Roles::AUTHORITY));
		assert!(ctx.has_message(peer_a.clone(), Message::SessionKey(local_key)));
191
192
193
194
195
	}

	// peer A gives session key and gets asked for data.
	{
		let mut ctx = TestContext::default();
196
		on_message(&mut protocol, &mut ctx, peer_a.clone(), Message::SessionKey(a_key.clone()));
197
		assert!(protocol.validators.contains_key(&a_key));
198
		assert!(ctx.has_message(peer_a.clone(), Message::RequestPovBlock(1, parent_hash, candidate_hash)));
199
200
	}

Gav Wood's avatar
Gav Wood committed
201
	knowledge.lock().note_statement(b_key.clone(), &GenericStatement::Valid(candidate_hash));
202
203
204
205

	// peer B connects and sends session key. request already assigned to A
	{
		let mut ctx = TestContext::default();
206
207
		protocol.on_connect(&mut ctx, peer_b.clone(), make_status(&status, Roles::AUTHORITY));
		on_message(&mut protocol, &mut ctx, peer_b.clone(), Message::SessionKey(b_key.clone()));
208
		assert!(!ctx.has_message(peer_b.clone(), Message::RequestPovBlock(2, parent_hash, candidate_hash)));
209
210
211
212
213
214

	}

	// peer A disconnects, triggering reassignment
	{
		let mut ctx = TestContext::default();
215
		protocol.on_disconnect(&mut ctx, peer_a.clone());
216
		assert!(!protocol.validators.contains_key(&a_key));
217
		assert!(ctx.has_message(peer_b.clone(), Message::RequestPovBlock(2, parent_hash, candidate_hash)));
218
219
220
221
222
	}

	// peer B comes back with block data.
	{
		let mut ctx = TestContext::default();
223
224
		let pov_block = make_pov(block_data.0);
		on_message(&mut protocol, &mut ctx, peer_b, Message::PovBlock(2, Some(pov_block.clone())));
225
		drop(protocol);
226
		assert_eq!(recv.wait().unwrap(), pov_block);
227
228
	}
}
229

230
231
232
233
#[test]
fn fetches_available_block_data() {
	let mut protocol = PolkadotProtocol::new(None);

234
	let peer_a = PeerId::random();
235
236
237
238
239
240
241
	let parent_hash = [0; 32].into();

	let block_data = BlockData(vec![1, 2, 3, 4]);
	let block_data_hash = block_data.hash();
	let para_id = 5.into();
	let candidate_receipt = CandidateReceipt {
		parachain_index: para_id,
Gav Wood's avatar
Gav Wood committed
242
		collator: [255; 32].unchecked_into(),
243
		head_data: HeadData(vec![9, 9, 9]),
Gav Wood's avatar
Gav Wood committed
244
		signature: Default::default(),
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
		balance_uploads: Vec::new(),
		egress_queue_roots: Vec::new(),
		fees: 1_000_000,
		block_data_hash,
	};

	let candidate_hash = candidate_receipt.hash();
	let av_store = ::av_store::Store::new_in_memory();

	let status = Status { collating_for: None };

	protocol.register_availability_store(av_store.clone());

	av_store.make_available(::av_store::Data {
		relay_parent: parent_hash,
		parachain_id: para_id,
		candidate_hash,
		block_data: block_data.clone(),
		extrinsic: None,
	}).unwrap();

	// connect peer A
	{
		let mut ctx = TestContext::default();
269
		protocol.on_connect(&mut ctx, peer_a.clone(), make_status(&status, Roles::FULL));
270
271
272
273
274
	}

	// peer A asks for historic block data and gets response
	{
		let mut ctx = TestContext::default();
275
		on_message(&mut protocol, &mut ctx, peer_a.clone(), Message::RequestBlockData(1, parent_hash, candidate_hash));
276
277
278
279
		assert!(ctx.has_message(peer_a, Message::BlockData(1, Some(block_data))));
	}
}

280
281
#[test]
fn remove_bad_collator() {
282
	let mut protocol = PolkadotProtocol::new(None);
283

284
	let who = PeerId::random();
Gav Wood's avatar
Gav Wood committed
285
	let collator_id: CollatorId = [2; 32].unchecked_into();
286

Gav Wood's avatar
Gav Wood committed
287
	let status = Status { collating_for: Some((collator_id.clone(), 5.into())) };
288
289
290

	{
		let mut ctx = TestContext::default();
291
		protocol.on_connect(&mut ctx, who.clone(), make_status(&status, Roles::NONE));
292
293
294
295
	}

	{
		let mut ctx = TestContext::default();
Gav Wood's avatar
Gav Wood committed
296
		protocol.disconnect_bad_collator(&mut ctx, collator_id);
Gav Wood's avatar
Gav Wood committed
297
		assert!(ctx.disabled.contains(&who));
298
299
	}
}
300
301
302
303
304
305
306
307

#[test]
fn many_session_keys() {
	let mut protocol = PolkadotProtocol::new(None);

	let parent_a = [1; 32].into();
	let parent_b = [2; 32].into();

Gav Wood's avatar
Gav Wood committed
308
309
	let local_key_a: ValidatorId = [3; 32].unchecked_into();
	let local_key_b: ValidatorId = [4; 32].unchecked_into();
310

311
312
	let params_a = make_validation_session(parent_a, local_key_a.clone());
	let params_b = make_validation_session(parent_b, local_key_b.clone());
313

314
315
	protocol.new_validation_session(&mut TestContext::default(), params_a);
	protocol.new_validation_session(&mut TestContext::default(), params_b);
316

Gav Wood's avatar
Gav Wood committed
317
	assert_eq!(protocol.live_validation_sessions.recent_keys(), &[local_key_a.clone(), local_key_b.clone()]);
318

319
	let peer_a = PeerId::random();
320
321
322
323
324
325

	// when connecting a peer, we should get both those keys.
	{
		let mut ctx = TestContext::default();

		let status = Status { collating_for: None };
326
		protocol.on_connect(&mut ctx, peer_a.clone(), make_status(&status, Roles::AUTHORITY));
327

328
		assert!(ctx.has_message(peer_a.clone(), Message::SessionKey(local_key_a.clone())));
Gav Wood's avatar
Gav Wood committed
329
		assert!(ctx.has_message(peer_a, Message::SessionKey(local_key_b.clone())));
330
331
	}

332
	let peer_b = PeerId::random();
333

334
	assert!(protocol.remove_validation_session(parent_a));
335
336
337
338
339

	{
		let mut ctx = TestContext::default();

		let status = Status { collating_for: None };
340
		protocol.on_connect(&mut ctx, peer_b.clone(), make_status(&status, Roles::AUTHORITY));
341

342
343
		assert!(!ctx.has_message(peer_b.clone(), Message::SessionKey(local_key_a.clone())));
		assert!(ctx.has_message(peer_b, Message::SessionKey(local_key_b.clone())));
344
345
	}
}