mod.rs 11 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 std::collections::HashMap;
20
use super::{PolkadotProtocol, Status, Message, FullStatus};
21
use crate::validation::SessionParams;
22

23
use polkadot_validation::GenericStatement;
24
use polkadot_primitives::{Block, Hash};
25
26
use polkadot_primitives::parachain::{
	CandidateReceipt, HeadData, PoVBlock, BlockData, CollatorId, ValidatorId,
27
	StructuredUnroutedIngress
28
};
Gav Wood's avatar
Gav Wood committed
29
use substrate_primitives::crypto::UncheckedInto;
30
use codec::Encode;
31
use substrate_network::{
32
33
	PeerId, Context, config::Roles, message::generic::ConsensusMessage,
	specialization::NetworkSpecialization,
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
	reputations: HashMap<PeerId, i32>,
45
	messages: Vec<(PeerId, Vec<u8>)>,
46
47
48
}

impl Context<Block> for TestContext {
49
	fn report_peer(&mut self, peer: PeerId, reputation: i32) {
50
51
52
        let reputation = self.reputations.get(&peer).map_or(reputation, |v| v + reputation);
        self.reputations.insert(peer.clone(), reputation);

53
54
55
56
		match reputation {
			i if i < -100 => self.disabled.push(peer),
			i if i < 0 => self.disconnected.push(peer),
			_ => {}
57
		}
58
59
	}

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

64
	fn send_chain_specific(&mut self, who: PeerId, message: Vec<u8>) {
65
		self.messages.push((who, message))
66
	}
67
68

	fn disconnect_peer(&mut self, _who: PeerId) { }
69
70
71
}

impl TestContext {
72
	fn has_message(&self, to: PeerId, message: Message) -> bool {
73
		let encoded = message.encode();
74
75
76
		self.messages.iter().any(|&(ref peer, ref data)|
			peer == &to && data == &encoded
		)
77
78
79
	}
}

80
81
82
83
84
85
86
fn make_pov(block_data: Vec<u8>) -> PoVBlock {
	PoVBlock {
		block_data: BlockData(block_data),
		ingress: polkadot_primitives::parachain::ConsolidatedIngress(Vec::new()),
	}
}

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

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

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

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

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

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

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

	{
		let mut ctx = TestContext::default();
132
133
		let params = make_validation_session(parent_hash, local_key.clone());
		protocol.new_validation_session(&mut ctx, params);
134
		assert!(ctx.has_message(peer_a, Message::ValidatorId(local_key.clone())));
135
136
137
138
	}

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

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

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

	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
157
		collator: [255; 32].unchecked_into(),
158
		head_data: HeadData(vec![9, 9, 9]),
Gav Wood's avatar
Gav Wood committed
159
		signature: Default::default(),
160
161
162
		egress_queue_roots: Vec::new(),
		fees: 1_000_000,
		block_data_hash,
163
		upward_messages: Vec::new(),
164
165
166
	};

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

	let status = Status { collating_for: None };

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

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

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

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

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

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

	}

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

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

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

233
	let peer_a = PeerId::random();
234
235
236
237
238
239
240
	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
241
		collator: [255; 32].unchecked_into(),
242
		head_data: HeadData(vec![9, 9, 9]),
Gav Wood's avatar
Gav Wood committed
243
		signature: Default::default(),
244
245
246
		egress_queue_roots: Vec::new(),
		fees: 1_000_000,
		block_data_hash,
247
		upward_messages: Vec::new(),
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
	};

	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();
268
		protocol.on_connect(&mut ctx, peer_a.clone(), make_status(&status, Roles::FULL));
269
270
271
272
273
	}

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

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

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

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

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

	{
		let mut ctx = TestContext::default();
Gav Wood's avatar
Gav Wood committed
295
		protocol.disconnect_bad_collator(&mut ctx, collator_id);
Gav Wood's avatar
Gav Wood committed
296
		assert!(ctx.disabled.contains(&who));
297
298
	}
}
299

300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#[test]
fn kick_collator() {
    let mut protocol = PolkadotProtocol::new(None);

    let who = PeerId::random();
    let collator_id: CollatorId = [2; 32].unchecked_into();

    let mut ctx = TestContext::default();
    let status = Status { collating_for: Some((collator_id.clone(), 5.into())) };
    protocol.on_connect(&mut ctx, who.clone(), make_status(&status, Roles::NONE));
    assert!(!ctx.disconnected.contains(&who));

    protocol.on_connect(&mut ctx, who.clone(), make_status(&status, Roles::NONE));
    assert!(ctx.disconnected.contains(&who));
}

316
317
318
319
320
321
322
#[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
323
324
	let local_key_a: ValidatorId = [3; 32].unchecked_into();
	let local_key_b: ValidatorId = [4; 32].unchecked_into();
325

326
327
	let params_a = make_validation_session(parent_a, local_key_a.clone());
	let params_b = make_validation_session(parent_b, local_key_b.clone());
328

329
330
	protocol.new_validation_session(&mut TestContext::default(), params_a);
	protocol.new_validation_session(&mut TestContext::default(), params_b);
331

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

334
	let peer_a = PeerId::random();
335
336
337
338
339
340

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

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

343
344
		assert!(ctx.has_message(peer_a.clone(), Message::ValidatorId(local_key_a.clone())));
		assert!(ctx.has_message(peer_a, Message::ValidatorId(local_key_b.clone())));
345
346
	}

347
	let peer_b = PeerId::random();
348

349
	assert!(protocol.remove_validation_session(parent_a));
350
351
352
353
354

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

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

357
358
		assert!(!ctx.has_message(peer_b.clone(), Message::ValidatorId(local_key_a.clone())));
		assert!(ctx.has_message(peer_b, Message::ValidatorId(local_key_b.clone())));
359
360
	}
}