mod.rs 10.3 KB
Newer Older
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1
// Copyright 2018-2020 Parity Technologies (UK) Ltd.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 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::LeafWorkParams;
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
};
29
use sp_core::crypto::UncheckedInto;
30
use codec::Encode;
31
use sc_network::{
32
	PeerId, Context, ReputationChange, config::Roles, message::generic::ConsensusMessage,
33
	specialization::NetworkSpecialization,
34
};
35

36
use futures::executor::block_on;
37

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: ReputationChange) {
Gavin Wood's avatar
Gavin Wood committed
50
51
		let reputation = self.reputations.get(&peer).map_or(reputation.value, |v| v + reputation.value);
		self.reputations.insert(peer.clone(), reputation);
52

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
	}

Gavin Wood's avatar
Gavin Wood committed
60
61
62
63
	fn send_consensus(&mut self, _who: PeerId, _consensus: Vec<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
87
88
89
90
91
#[derive(Default)]
pub struct TestChainContext {
	pub known_map: HashMap<Hash, crate::gossip::Known>,
	pub ingress_roots: HashMap<Hash, Vec<Hash>>,
}

impl crate::gossip::ChainContext for TestChainContext {
	fn is_known(&self, block_hash: &Hash) -> Option<crate::gossip::Known> {
		self.known_map.get(block_hash).map(|x| x.clone())
	}

	fn leaf_unrouted_roots(&self, leaf: &Hash, with_queue_root: &mut dyn FnMut(&Hash))
Gavin Wood's avatar
Gavin Wood committed
92
		-> Result<(), sp_blockchain::Error>
93
94
95
96
97
98
99
100
101
	{
		for root in self.ingress_roots.get(leaf).into_iter().flat_map(|roots| roots) {
			with_queue_root(root)
		}

		Ok(())
	}
}

102
103
104
105
106
107
108
fn make_pov(block_data: Vec<u8>) -> PoVBlock {
	PoVBlock {
		block_data: BlockData(block_data),
		ingress: polkadot_primitives::parachain::ConsolidatedIngress(Vec::new()),
	}
}

109
fn make_status(status: &Status, roles: Roles) -> FullStatus {
110
111
	FullStatus {
		version: 1,
112
		min_supported_version: 1,
113
114
115
116
117
118
119
120
		roles,
		best_number: 0,
		best_hash: Default::default(),
		genesis_hash: Default::default(),
		chain_status: status.encode(),
	}
}

121
122
fn make_validation_leaf_work(parent_hash: Hash, local_key: ValidatorId) -> LeafWorkParams {
	LeafWorkParams {
123
124
125
126
		local_session_key: Some(local_key),
		parent_hash,
		authorities: Vec::new(),
	}
127
128
}

129
fn on_message(protocol: &mut PolkadotProtocol, ctx: &mut TestContext, from: PeerId, message: Message) {
130
	let encoded = message.encode();
131
	protocol.on_message(ctx, from, encoded);
132
133
134
135
}

#[test]
fn sends_session_key() {
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
	let validator_status = Status { collating_for: None };
Gav Wood's avatar
Gav Wood committed
144
	let collator_status = Status { collating_for: Some(([2; 32].unchecked_into(), 5.into())) };
145
146
147

	{
		let mut ctx = TestContext::default();
148
		protocol.on_connect(&mut ctx, peer_a.clone(), make_status(&validator_status, Roles::AUTHORITY));
149
150
151
152
153
		assert!(ctx.messages.is_empty());
	}

	{
		let mut ctx = TestContext::default();
154
155
		let params = make_validation_leaf_work(parent_hash, local_key.clone());
		protocol.new_validation_leaf_work(&mut ctx, params);
156
		assert!(ctx.has_message(peer_a, Message::ValidatorId(local_key.clone())));
157
158
159
160
	}

	{
		let mut ctx = TestContext::default();
161
		protocol.on_connect(&mut ctx, peer_b.clone(), make_status(&collator_status, Roles::NONE));
162
		assert!(ctx.has_message(peer_b.clone(), Message::ValidatorId(local_key)));
163
164
165
166
167
	}
}

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

170
171
	let peer_a = PeerId::random();
	let peer_b = PeerId::random();
172
	let parent_hash = [0; 32].into();
Gav Wood's avatar
Gav Wood committed
173
	let local_key: ValidatorId = [1; 32].unchecked_into();
174
175
176
177
178

	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
179
		collator: [255; 32].unchecked_into(),
180
		head_data: HeadData(vec![9, 9, 9]),
Gav Wood's avatar
Gav Wood committed
181
		signature: Default::default(),
182
183
184
		egress_queue_roots: Vec::new(),
		fees: 1_000_000,
		block_data_hash,
185
		upward_messages: Vec::new(),
186
		erasure_root: [1u8; 32].into(),
187
188
189
	};

	let candidate_hash = candidate_receipt.hash();
Gav Wood's avatar
Gav Wood committed
190
191
	let a_key: ValidatorId = [3; 32].unchecked_into();
	let b_key: ValidatorId = [4; 32].unchecked_into();
192
193
194

	let status = Status { collating_for: None };

195
196
	let params = make_validation_leaf_work(parent_hash, local_key.clone());
	let session = protocol.new_validation_leaf_work(&mut TestContext::default(), params);
197
	let knowledge = session.knowledge();
198

Gav Wood's avatar
Gav Wood committed
199
	knowledge.lock().note_statement(a_key.clone(), &GenericStatement::Valid(candidate_hash));
200
	let canon_roots = StructuredUnroutedIngress(Vec::new());
201
202
203
204
205
206
	let recv = protocol.fetch_pov_block(
		&mut TestContext::default(),
		&candidate_receipt,
		parent_hash,
		canon_roots,
	);
207
208
209
210

	// connect peer A
	{
		let mut ctx = TestContext::default();
211
		protocol.on_connect(&mut ctx, peer_a.clone(), make_status(&status, Roles::AUTHORITY));
212
		assert!(ctx.has_message(peer_a.clone(), Message::ValidatorId(local_key)));
213
214
215
216
217
	}

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

Gav Wood's avatar
Gav Wood committed
223
	knowledge.lock().note_statement(b_key.clone(), &GenericStatement::Valid(candidate_hash));
224
225
226
227

	// peer B connects and sends session key. request already assigned to A
	{
		let mut ctx = TestContext::default();
228
		protocol.on_connect(&mut ctx, peer_b.clone(), make_status(&status, Roles::AUTHORITY));
229
		on_message(&mut protocol, &mut ctx, peer_b.clone(), Message::ValidatorId(b_key.clone()));
230
		assert!(!ctx.has_message(peer_b.clone(), Message::RequestPovBlock(2, parent_hash, candidate_hash)));
231
232
233
234
235
236

	}

	// peer A disconnects, triggering reassignment
	{
		let mut ctx = TestContext::default();
237
		protocol.on_disconnect(&mut ctx, peer_a.clone());
238
		assert!(!protocol.validators.contains_key(&a_key));
239
		assert!(ctx.has_message(peer_b.clone(), Message::RequestPovBlock(2, parent_hash, candidate_hash)));
240
241
242
243
244
	}

	// peer B comes back with block data.
	{
		let mut ctx = TestContext::default();
245
246
		let pov_block = make_pov(block_data.0);
		on_message(&mut protocol, &mut ctx, peer_b, Message::PovBlock(2, Some(pov_block.clone())));
247
		drop(protocol);
248
		assert_eq!(block_on(recv).unwrap(), pov_block);
249
250
	}
}
251
252
253

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

256
	let who = PeerId::random();
Gav Wood's avatar
Gav Wood committed
257
	let collator_id: CollatorId = [2; 32].unchecked_into();
258

Gav Wood's avatar
Gav Wood committed
259
	let status = Status { collating_for: Some((collator_id.clone(), 5.into())) };
260
261
262

	{
		let mut ctx = TestContext::default();
263
		protocol.on_connect(&mut ctx, who.clone(), make_status(&status, Roles::NONE));
264
265
266
267
	}

	{
		let mut ctx = TestContext::default();
Gav Wood's avatar
Gav Wood committed
268
		protocol.disconnect_bad_collator(&mut ctx, collator_id);
Gav Wood's avatar
Gav Wood committed
269
		assert!(ctx.disabled.contains(&who));
270
271
	}
}
272

273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#[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));
}

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

299
300
	let params_a = make_validation_leaf_work(parent_a, local_key_a.clone());
	let params_b = make_validation_leaf_work(parent_b, local_key_b.clone());
301

302
303
	protocol.new_validation_leaf_work(&mut TestContext::default(), params_a);
	protocol.new_validation_leaf_work(&mut TestContext::default(), params_b);
304

305
	assert_eq!(protocol.live_validation_leaves.recent_keys(), &[local_key_a.clone(), local_key_b.clone()]);
306

307
	let peer_a = PeerId::random();
308
309
310
311
312
313

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

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

316
317
		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())));
318
319
	}

320
	let peer_b = PeerId::random();
321

322
	assert!(protocol.remove_validation_session(parent_a));
323
324
325
326
327

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

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

330
331
		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())));
332
333
	}
}