mod.rs 10.2 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};
Gav Wood's avatar
Gav Wood committed
24
25
use polkadot_primitives::parachain::{CandidateReceipt, HeadData, BlockData, CollatorId, ValidatorId};
use substrate_primitives::crypto::UncheckedInto;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
26
use codec::Encode;
27
use substrate_network::{
28
	Severity, PeerId, PeerInfo, ClientHandle, Context, config::Roles,
29
30
31
	message::Message as SubstrateMessage, specialization::NetworkSpecialization,
	generic_message::Message as GenericMessage
};
32
33
34

use futures::Future;

35
mod validation;
36

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

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

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

56
	fn peer_info(&self, _peer: &PeerId) -> Option<PeerInfo<Block>> {
57
58
59
		unimplemented!()
	}

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

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

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

77
fn make_status(status: &Status, roles: Roles) -> FullStatus {
78
79
	FullStatus {
		version: 1,
80
		min_supported_version: 1,
81
82
83
84
85
86
87
88
		roles,
		best_number: 0,
		best_hash: Default::default(),
		genesis_hash: Default::default(),
		chain_status: status.encode(),
	}
}

89
90
91
92
93
94
fn make_validation_session(parent_hash: Hash, local_key: SessionKey) -> SessionParams {
	SessionParams {
		local_session_key: Some(local_key),
		parent_hash,
		authorities: Vec::new(),
	}
95
96
}

97
fn on_message(protocol: &mut PolkadotProtocol, ctx: &mut TestContext, from: PeerId, message: Message) {
98
	let encoded = message.encode();
99
	protocol.on_message(ctx, from, &mut Some(GenericMessage::ChainSpecific(encoded)));
100
101
102
103
}

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

106
107
	let peer_a = PeerId::random();
	let peer_b = PeerId::random();
108
	let parent_hash = [0; 32].into();
Gav Wood's avatar
Gav Wood committed
109
	let local_key: ValidatorId = [1; 32].unchecked_into();
110

111
	let validator_status = Status { collating_for: None };
Gav Wood's avatar
Gav Wood committed
112
	let collator_status = Status { collating_for: Some(([2; 32].unchecked_into(), 5.into())) };
113
114
115

	{
		let mut ctx = TestContext::default();
116
		protocol.on_connect(&mut ctx, peer_a.clone(), make_status(&validator_status, Roles::AUTHORITY));
117
118
119
120
121
		assert!(ctx.messages.is_empty());
	}

	{
		let mut ctx = TestContext::default();
122
123
		let params = make_validation_session(parent_hash, local_key.clone());
		protocol.new_validation_session(&mut ctx, params);
Gav Wood's avatar
Gav Wood committed
124
		assert!(ctx.has_message(peer_a, Message::SessionKey(local_key.clone())));
125
126
127
128
	}

	{
		let mut ctx = TestContext::default();
129
130
		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)));
131
132
133
134
135
	}
}

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

138
139
	let peer_a = PeerId::random();
	let peer_b = PeerId::random();
140
	let parent_hash = [0; 32].into();
Gav Wood's avatar
Gav Wood committed
141
	let local_key: ValidatorId = [1; 32].unchecked_into();
142
143
144
145
146

	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
147
		collator: [255; 32].unchecked_into(),
148
		head_data: HeadData(vec![9, 9, 9]),
Gav Wood's avatar
Gav Wood committed
149
		signature: Default::default(),
150
151
152
153
154
155
156
		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
157
158
	let a_key: ValidatorId = [3; 32].unchecked_into();
	let b_key: ValidatorId = [4; 32].unchecked_into();
159
160
161

	let status = Status { collating_for: None };

162
163
164
	let params = make_validation_session(parent_hash, local_key.clone());
	let session = protocol.new_validation_session(&mut TestContext::default(), params);
	let knowledge = session.knowledge();
165

Gav Wood's avatar
Gav Wood committed
166
	knowledge.lock().note_statement(a_key.clone(), &GenericStatement::Valid(candidate_hash));
167
168
169
170
171
	let recv = protocol.fetch_block_data(&mut TestContext::default(), &candidate_receipt, parent_hash);

	// connect peer A
	{
		let mut ctx = TestContext::default();
172
173
		protocol.on_connect(&mut ctx, peer_a.clone(), make_status(&status, Roles::AUTHORITY));
		assert!(ctx.has_message(peer_a.clone(), Message::SessionKey(local_key)));
174
175
176
177
178
	}

	// peer A gives session key and gets asked for data.
	{
		let mut ctx = TestContext::default();
179
		on_message(&mut protocol, &mut ctx, peer_a.clone(), Message::SessionKey(a_key.clone()));
180
		assert!(protocol.validators.contains_key(&a_key));
181
		assert!(ctx.has_message(peer_a.clone(), Message::RequestBlockData(1, parent_hash, candidate_hash)));
182
183
	}

Gav Wood's avatar
Gav Wood committed
184
	knowledge.lock().note_statement(b_key.clone(), &GenericStatement::Valid(candidate_hash));
185
186
187
188

	// peer B connects and sends session key. request already assigned to A
	{
		let mut ctx = TestContext::default();
189
190
191
		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()));
		assert!(!ctx.has_message(peer_b.clone(), Message::RequestBlockData(2, parent_hash, candidate_hash)));
192
193
194
195
196
197

	}

	// peer A disconnects, triggering reassignment
	{
		let mut ctx = TestContext::default();
198
		protocol.on_disconnect(&mut ctx, peer_a.clone());
199
		assert!(!protocol.validators.contains_key(&a_key));
200
		assert!(ctx.has_message(peer_b.clone(), Message::RequestBlockData(2, parent_hash, candidate_hash)));
201
202
203
204
205
206
207
208
209
210
	}

	// peer B comes back with block data.
	{
		let mut ctx = TestContext::default();
		on_message(&mut protocol, &mut ctx, peer_b, Message::BlockData(2, Some(block_data.clone())));
		drop(protocol);
		assert_eq!(recv.wait().unwrap(), block_data);
	}
}
211

212
213
214
215
#[test]
fn fetches_available_block_data() {
	let mut protocol = PolkadotProtocol::new(None);

216
	let peer_a = PeerId::random();
217
218
219
220
221
222
223
	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
224
		collator: [255; 32].unchecked_into(),
225
		head_data: HeadData(vec![9, 9, 9]),
Gav Wood's avatar
Gav Wood committed
226
		signature: Default::default(),
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
		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();
251
		protocol.on_connect(&mut ctx, peer_a.clone(), make_status(&status, Roles::FULL));
252
253
254
255
256
	}

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

262
263
#[test]
fn remove_bad_collator() {
264
	let mut protocol = PolkadotProtocol::new(None);
265

266
	let who = PeerId::random();
Gav Wood's avatar
Gav Wood committed
267
	let collator_id: CollatorId = [2; 32].unchecked_into();
268

Gav Wood's avatar
Gav Wood committed
269
	let status = Status { collating_for: Some((collator_id.clone(), 5.into())) };
270
271
272

	{
		let mut ctx = TestContext::default();
273
		protocol.on_connect(&mut ctx, who.clone(), make_status(&status, Roles::NONE));
274
275
276
277
	}

	{
		let mut ctx = TestContext::default();
Gav Wood's avatar
Gav Wood committed
278
		protocol.disconnect_bad_collator(&mut ctx, collator_id);
Gav Wood's avatar
Gav Wood committed
279
		assert!(ctx.disabled.contains(&who));
280
281
	}
}
282
283
284
285
286
287
288
289

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

293
294
	let params_a = make_validation_session(parent_a, local_key_a.clone());
	let params_b = make_validation_session(parent_b, local_key_b.clone());
295

296
297
	protocol.new_validation_session(&mut TestContext::default(), params_a);
	protocol.new_validation_session(&mut TestContext::default(), params_b);
298

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

301
	let peer_a = PeerId::random();
302
303
304
305
306
307

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

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

310
		assert!(ctx.has_message(peer_a.clone(), Message::SessionKey(local_key_a.clone())));
Gav Wood's avatar
Gav Wood committed
311
		assert!(ctx.has_message(peer_a, Message::SessionKey(local_key_b.clone())));
312
313
	}

314
	let peer_b = PeerId::random();
315

316
	assert!(protocol.remove_validation_session(parent_a));
317
318
319
320
321

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

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

324
325
		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())));
326
327
	}
}