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
	message::{BlockRequest, generic::ConsensusMessage},
	specialization::NetworkSpecialization, generic_message::Message as GenericMessage
34
};
35
36
37

use futures::Future;

38
mod validation;
39

40
41
#[derive(Default)]
struct TestContext {
42
43
	disabled: Vec<PeerId>,
	disconnected: Vec<PeerId>,
44
	messages: Vec<(PeerId, Vec<u8>)>,
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
64
65
66
67
68
69
70
71
72
	fn send_block_request(&mut self, _who: PeerId, _request: BlockRequest<Block>) {
		unimplemented!()
	}

	fn send_consensus(&mut self, _who: PeerId, _consensus: ConsensusMessage) {
		unimplemented!()
	}

	fn send_chain_specific(&mut self, who: PeerId, message: Vec<u8>){
		self.messages.push((who, message))
73
74
75
76
	}
}

impl TestContext {
77
	fn has_message(&self, to: PeerId, message: Message) -> bool {
78
		let encoded = message.encode();
79
80
81
		self.messages.iter().any(|&(ref peer, ref data)|
			peer == &to && data == &encoded
		)
82
83
84
	}
}

85
86
87
88
89
90
91
92

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

93
fn make_status(status: &Status, roles: Roles) -> FullStatus {
94
95
	FullStatus {
		version: 1,
96
		min_supported_version: 1,
97
98
99
100
101
102
103
104
		roles,
		best_number: 0,
		best_hash: Default::default(),
		genesis_hash: Default::default(),
		chain_status: status.encode(),
	}
}

105
106
107
108
109
110
fn make_validation_session(parent_hash: Hash, local_key: SessionKey) -> SessionParams {
	SessionParams {
		local_session_key: Some(local_key),
		parent_hash,
		authorities: Vec::new(),
	}
111
112
}

113
fn on_message(protocol: &mut PolkadotProtocol, ctx: &mut TestContext, from: PeerId, message: Message) {
114
	let encoded = message.encode();
115
	protocol.on_message(ctx, from, &mut Some(GenericMessage::ChainSpecific(encoded)));
116
117
118
119
}

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

122
123
	let peer_a = PeerId::random();
	let peer_b = PeerId::random();
124
	let parent_hash = [0; 32].into();
Gav Wood's avatar
Gav Wood committed
125
	let local_key: ValidatorId = [1; 32].unchecked_into();
126

127
	let validator_status = Status { collating_for: None };
Gav Wood's avatar
Gav Wood committed
128
	let collator_status = Status { collating_for: Some(([2; 32].unchecked_into(), 5.into())) };
129
130
131

	{
		let mut ctx = TestContext::default();
132
		protocol.on_connect(&mut ctx, peer_a.clone(), make_status(&validator_status, Roles::AUTHORITY));
133
134
135
136
137
		assert!(ctx.messages.is_empty());
	}

	{
		let mut ctx = TestContext::default();
138
139
		let params = make_validation_session(parent_hash, local_key.clone());
		protocol.new_validation_session(&mut ctx, params);
Gav Wood's avatar
Gav Wood committed
140
		assert!(ctx.has_message(peer_a, Message::SessionKey(local_key.clone())));
141
142
143
144
	}

	{
		let mut ctx = TestContext::default();
145
146
		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)));
147
148
149
150
151
	}
}

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

154
155
	let peer_a = PeerId::random();
	let peer_b = PeerId::random();
156
	let parent_hash = [0; 32].into();
Gav Wood's avatar
Gav Wood committed
157
	let local_key: ValidatorId = [1; 32].unchecked_into();
158
159
160
161
162

	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
163
		collator: [255; 32].unchecked_into(),
164
		head_data: HeadData(vec![9, 9, 9]),
Gav Wood's avatar
Gav Wood committed
165
		signature: Default::default(),
166
167
168
169
170
171
172
		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
173
174
	let a_key: ValidatorId = [3; 32].unchecked_into();
	let b_key: ValidatorId = [4; 32].unchecked_into();
175
176
177

	let status = Status { collating_for: None };

178
179
180
	let params = make_validation_session(parent_hash, local_key.clone());
	let session = protocol.new_validation_session(&mut TestContext::default(), params);
	let knowledge = session.knowledge();
181

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

	// connect peer A
	{
		let mut ctx = TestContext::default();
194
195
		protocol.on_connect(&mut ctx, peer_a.clone(), make_status(&status, Roles::AUTHORITY));
		assert!(ctx.has_message(peer_a.clone(), Message::SessionKey(local_key)));
196
197
198
199
200
	}

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

Gav Wood's avatar
Gav Wood committed
206
	knowledge.lock().note_statement(b_key.clone(), &GenericStatement::Valid(candidate_hash));
207
208
209
210

	// peer B connects and sends session key. request already assigned to A
	{
		let mut ctx = TestContext::default();
211
212
		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()));
213
		assert!(!ctx.has_message(peer_b.clone(), Message::RequestPovBlock(2, parent_hash, candidate_hash)));
214
215
216
217
218
219

	}

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

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

235
236
237
238
#[test]
fn fetches_available_block_data() {
	let mut protocol = PolkadotProtocol::new(None);

239
	let peer_a = PeerId::random();
240
241
242
243
244
245
246
	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
247
		collator: [255; 32].unchecked_into(),
248
		head_data: HeadData(vec![9, 9, 9]),
Gav Wood's avatar
Gav Wood committed
249
		signature: Default::default(),
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
		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();
274
		protocol.on_connect(&mut ctx, peer_a.clone(), make_status(&status, Roles::FULL));
275
276
277
278
279
	}

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

285
286
#[test]
fn remove_bad_collator() {
287
	let mut protocol = PolkadotProtocol::new(None);
288

289
	let who = PeerId::random();
Gav Wood's avatar
Gav Wood committed
290
	let collator_id: CollatorId = [2; 32].unchecked_into();
291

Gav Wood's avatar
Gav Wood committed
292
	let status = Status { collating_for: Some((collator_id.clone(), 5.into())) };
293
294
295

	{
		let mut ctx = TestContext::default();
296
		protocol.on_connect(&mut ctx, who.clone(), make_status(&status, Roles::NONE));
297
298
299
300
	}

	{
		let mut ctx = TestContext::default();
Gav Wood's avatar
Gav Wood committed
301
		protocol.disconnect_bad_collator(&mut ctx, collator_id);
Gav Wood's avatar
Gav Wood committed
302
		assert!(ctx.disabled.contains(&who));
303
304
	}
}
305
306
307
308
309
310
311
312

#[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
313
314
	let local_key_a: ValidatorId = [3; 32].unchecked_into();
	let local_key_b: ValidatorId = [4; 32].unchecked_into();
315

316
317
	let params_a = make_validation_session(parent_a, local_key_a.clone());
	let params_b = make_validation_session(parent_b, local_key_b.clone());
318

319
320
	protocol.new_validation_session(&mut TestContext::default(), params_a);
	protocol.new_validation_session(&mut TestContext::default(), params_b);
321

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

324
	let peer_a = PeerId::random();
325
326
327
328
329
330

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

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

333
		assert!(ctx.has_message(peer_a.clone(), Message::SessionKey(local_key_a.clone())));
Gav Wood's avatar
Gav Wood committed
334
		assert!(ctx.has_message(peer_a, Message::SessionKey(local_key_b.clone())));
335
336
	}

337
	let peer_b = PeerId::random();
338

339
	assert!(protocol.remove_validation_session(parent_a));
340
341
342
343
344

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

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

347
348
		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())));
349
350
	}
}