lib.rs 41.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Copyright 2020 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/>.

//! The Network Bridge Subsystem - protocol multiplexer for Polkadot.

use parity_scale_codec::{Encode, Decode};
use futures::prelude::*;
use futures::future::BoxFuture;
use futures::stream::BoxStream;
23
use futures::channel::{mpsc, oneshot};
24

25
use sc_network::Event as NetworkEvent;
26
27
28
use sp_runtime::ConsensusEngineId;

use polkadot_subsystem::{
29
	ActiveLeavesUpdate, FromOverseer, OverseerSignal, Subsystem, SubsystemContext, SpawnedSubsystem, SubsystemError,
30
31
	SubsystemResult,
};
32
33
34
35
36
use polkadot_subsystem::messages::{
	NetworkBridgeMessage, AllMessages, AvailabilityDistributionMessage,
	BitfieldDistributionMessage, PoVDistributionMessage, StatementDistributionMessage,
	CollatorProtocolMessage,
};
37
use polkadot_primitives::v1::{AuthorityDiscoveryId, Block, Hash};
38
39
40
use polkadot_node_network_protocol::{
	ObservedRole, ReputationChange, PeerId, PeerSet, View, NetworkBridgeEvent, v1 as protocol_v1
};
41

42
use std::collections::{HashMap, hash_map};
43
use std::iter::ExactSizeIterator;
44
45
46
use std::pin::Pin;
use std::sync::Arc;

47
48
49

mod validator_discovery;

50
51
52
53
54
/// The maximum amount of heads a peer is allowed to have in their view at any time.
///
/// We use the same limit to compute the view sent to peers locally.
const MAX_VIEW_HEADS: usize = 5;

55
56
57
/// The engine ID of the validation protocol.
pub const VALIDATION_PROTOCOL_ID: ConsensusEngineId = *b"pvn1";
/// The protocol name for the validation peer-set.
58
pub const VALIDATION_PROTOCOL_NAME: &'static str = "/polkadot/validation/1";
59
60
61
/// The engine ID of the collation protocol.
pub const COLLATION_PROTOCOL_ID: ConsensusEngineId = *b"pcn1";
/// The protocol name for the collation peer-set.
62
pub const COLLATION_PROTOCOL_NAME: &'static str = "/polkadot/collation/1";
63
64
65

const MALFORMED_MESSAGE_COST: ReputationChange
	= ReputationChange::new(-500, "Malformed Network-bridge message");
66
67
const UNCONNECTED_PEERSET_COST: ReputationChange
	= ReputationChange::new(-50, "Message sent to un-connected peer-set");
68
69
70
const MALFORMED_VIEW_COST: ReputationChange
	= ReputationChange::new(-500, "Malformed view");

71
72
73
// network bridge log target
const TARGET: &'static str = "network_bridge";

74
75
/// Messages received on the network.
#[derive(Debug, Encode, Decode, Clone)]
76
pub enum WireMessage<M> {
77
78
	/// A message from a peer on a specific protocol.
	#[codec(index = "1")]
79
	ProtocolMessage(M),
80
81
82
83
84
85
86
	/// A view update from a peer.
	#[codec(index = "2")]
	ViewUpdate(View),
}

/// Information about the notifications protocol. Should be used during network configuration
/// or shortly after startup to register the protocol with the network service.
87
pub fn notifications_protocol_info() -> Vec<(ConsensusEngineId, std::borrow::Cow<'static, str>)> {
88
89
90
91
	vec![
		(VALIDATION_PROTOCOL_ID, VALIDATION_PROTOCOL_NAME.into()),
		(COLLATION_PROTOCOL_ID, COLLATION_PROTOCOL_NAME.into()),
	]
92
93
94
}

/// An action to be carried out by the network.
95
#[derive(Debug, PartialEq)]
96
97
98
pub enum NetworkAction {
	/// Note a change in reputation for a peer.
	ReputationChange(PeerId, ReputationChange),
99
100
	/// Write a notification to a given peer on the given peer-set.
	WriteNotification(PeerId, PeerSet, Vec<u8>),
101
102
103
104
105
106
}

/// An abstraction over networking for the purposes of this subsystem.
pub trait Network: Send + 'static {
	/// Get a stream of all events occurring on the network. This may include events unrelated
	/// to the Polkadot protocol - the user of this function should filter only for events related
107
108
	/// to the [`VALIDATION_PROTOCOL_ID`](VALIDATION_PROTOCOL_ID)
	/// or [`COLLATION_PROTOCOL_ID`](COLLATION_PROTOCOL_ID)
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
	fn event_stream(&mut self) -> BoxStream<'static, NetworkEvent>;

	/// Get access to an underlying sink for all network actions.
	fn action_sink<'a>(&'a mut self) -> Pin<
		Box<dyn Sink<NetworkAction, Error = SubsystemError> + Send + 'a>
	>;

	/// Report a given peer as either beneficial (+) or costly (-) according to the given scalar.
	fn report_peer(&mut self, who: PeerId, cost_benefit: ReputationChange)
		-> BoxFuture<SubsystemResult<()>>
	{
		async move {
			self.action_sink().send(NetworkAction::ReputationChange(who, cost_benefit)).await
		}.boxed()
	}

125
126
	/// Write a notification to a peer on the given peer-set's protocol.
	fn write_notification(&mut self, who: PeerId, peer_set: PeerSet, message: Vec<u8>)
127
128
129
		-> BoxFuture<SubsystemResult<()>>
	{
		async move {
130
			self.action_sink().send(NetworkAction::WriteNotification(who, peer_set, message)).await
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
		}.boxed()
	}
}

impl Network for Arc<sc_network::NetworkService<Block, Hash>> {
	fn event_stream(&mut self) -> BoxStream<'static, NetworkEvent> {
		sc_network::NetworkService::event_stream(self, "polkadot-network-bridge").boxed()
	}

	fn action_sink<'a>(&'a mut self)
		-> Pin<Box<dyn Sink<NetworkAction, Error = SubsystemError> + Send + 'a>>
	{
		use futures::task::{Poll, Context};

		// wrapper around a NetworkService to make it act like a sink.
		struct ActionSink<'b>(&'b sc_network::NetworkService<Block, Hash>);

		impl<'b> Sink<NetworkAction> for ActionSink<'b> {
			type Error = SubsystemError;

			fn poll_ready(self: Pin<&mut Self>, _: &mut Context) -> Poll<SubsystemResult<()>> {
				Poll::Ready(Ok(()))
			}

			fn start_send(self: Pin<&mut Self>, action: NetworkAction) -> SubsystemResult<()> {
				match action {
					NetworkAction::ReputationChange(peer, cost_benefit) => self.0.report_peer(
						peer,
						cost_benefit,
					),
161
162
163
164
165
166
167
168
169
170
171
172
173
174
					NetworkAction::WriteNotification(peer, peer_set, message) => {
						match peer_set {
							PeerSet::Validation => self.0.write_notification(
								peer,
								VALIDATION_PROTOCOL_ID,
								message,
							),
							PeerSet::Collation => self.0.write_notification(
								peer,
								COLLATION_PROTOCOL_ID,
								message,
							),
						}
					}
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
				}

				Ok(())
			}

			fn poll_flush(self: Pin<&mut Self>, _: &mut Context) -> Poll<SubsystemResult<()>> {
				Poll::Ready(Ok(()))
			}

			fn poll_close(self: Pin<&mut Self>, _: &mut Context) -> Poll<SubsystemResult<()>> {
				Poll::Ready(Ok(()))
			}
		}

		Box::pin(ActionSink(&**self))
	}
}

/// The network bridge subsystem.
194
195
196
197
pub struct NetworkBridge<N, AD> {
	network_service: N,
	authority_discovery_service: AD,
}
198

199
200
impl<N, AD> NetworkBridge<N, AD> {
	/// Create a new network bridge subsystem with underlying network service and authority discovery service.
201
202
203
	///
	/// This assumes that the network service has had the notifications protocol for the network
	/// bridge already registered. See [`notifications_protocol_info`](notifications_protocol_info).
204
205
206
207
208
	pub fn new(network_service: N, authority_discovery_service: AD) -> Self {
		NetworkBridge {
			network_service,
			authority_discovery_service,
		}
209
210
211
	}
}

212
impl<Net, AD, Context> Subsystem<Context> for NetworkBridge<Net, AD>
213
	where
214
215
		Net: Network + validator_discovery::Network,
		AD: validator_discovery::AuthorityDiscovery,
216
217
		Context: SubsystemContext<Message=NetworkBridgeMessage>,
{
218
219
220
	fn start(self, ctx: Context) -> SpawnedSubsystem {
		// Swallow error because failure is fatal to the node and we log with more precision
		// within `run_network`.
221
		let Self { network_service, authority_discovery_service } = self;
222
223
		SpawnedSubsystem {
			name: "network-bridge-subsystem",
224
225
226
227
228
			future: run_network(
				network_service,
				authority_discovery_service,
				ctx,
			).map(|_| ()).boxed(),
229
		}
230
231
232
233
234
235
236
237
238
239
	}
}

struct PeerData {
	/// Latest view sent by the peer.
	view: View,
}

#[derive(Debug)]
enum Action {
240
241
	SendValidationMessage(Vec<PeerId>, protocol_v1::ValidationProtocol),
	SendCollationMessage(Vec<PeerId>, protocol_v1::CollationProtocol),
242
243
244
245
246
	ConnectToValidators {
		validator_ids: Vec<AuthorityDiscoveryId>,
		connected: mpsc::Sender<(AuthorityDiscoveryId, PeerId)>,
		revoke: oneshot::Receiver<()>,
	},
247
	ReportPeer(PeerId, ReputationChange),
248

249
	ActiveLeaves(ActiveLeavesUpdate),
250

251
252
253
254
255
256
257
	PeerConnected(PeerSet, PeerId, ObservedRole),
	PeerDisconnected(PeerSet, PeerId),
	PeerMessages(
		PeerId,
		Vec<WireMessage<protocol_v1::ValidationProtocol>>,
		Vec<WireMessage<protocol_v1::CollationProtocol>>,
	),
258
259

	Abort,
260
	Nop,
261
262
263
264
265
266
}

fn action_from_overseer_message(
	res: polkadot_subsystem::SubsystemResult<FromOverseer<NetworkBridgeMessage>>,
) -> Action {
	match res {
267
268
		Ok(FromOverseer::Signal(OverseerSignal::ActiveLeaves(active_leaves)))
			=> Action::ActiveLeaves(active_leaves),
269
270
271
		Ok(FromOverseer::Signal(OverseerSignal::Conclude)) => Action::Abort,
		Ok(FromOverseer::Communication { msg }) => match msg {
			NetworkBridgeMessage::ReportPeer(peer, rep) => Action::ReportPeer(peer, rep),
272
273
274
275
			NetworkBridgeMessage::SendValidationMessage(peers, msg)
				=> Action::SendValidationMessage(peers, msg),
			NetworkBridgeMessage::SendCollationMessage(peers, msg)
				=> Action::SendCollationMessage(peers, msg),
276
277
278
279
280
			NetworkBridgeMessage::ConnectToValidators {
				validator_ids,
				connected,
				revoke,
			} => Action::ConnectToValidators { validator_ids, connected, revoke },
281
		},
282
283
		Ok(FromOverseer::Signal(OverseerSignal::BlockFinalized(_)))
			=> Action::Nop,
284
		Err(e) => {
285
			log::warn!(target: TARGET, "Shutting down Network Bridge due to error {:?}", e);
286
287
288
289
290
			Action::Abort
		}
	}
}

291
fn action_from_network_message(event: Option<NetworkEvent>) -> Action {
292
293
	match event {
		None => {
294
			log::info!(target: TARGET, "Shutting down Network Bridge: underlying event stream concluded");
295
			Action::Abort
296
		}
297
		Some(NetworkEvent::Dht(_)) => Action::Nop,
298
		Some(NetworkEvent::NotificationStreamOpened { remote, engine_id, role }) => {
299
300
301
302
303
304
305
			let role = role.into();
			match engine_id {
				x if x == VALIDATION_PROTOCOL_ID
					=> Action::PeerConnected(PeerSet::Validation, remote, role),
				x if x == COLLATION_PROTOCOL_ID
					=> Action::PeerConnected(PeerSet::Collation, remote, role),
				_ => Action::Nop,
306
307
308
			}
		}
		Some(NetworkEvent::NotificationStreamClosed { remote, engine_id }) => {
309
310
311
312
313
314
			match engine_id {
				x if x == VALIDATION_PROTOCOL_ID
					=> Action::PeerDisconnected(PeerSet::Validation, remote),
				x if x == COLLATION_PROTOCOL_ID
					=> Action::PeerDisconnected(PeerSet::Collation, remote),
				_ => Action::Nop,
315
316
317
			}
		}
		Some(NetworkEvent::NotificationsReceived { remote, messages }) => {
318
319
320
321
322
323
324
325
326
327
328
329
			let v_messages: Result<Vec<_>, _> = messages.iter()
				.filter(|(engine_id, _)| engine_id == &VALIDATION_PROTOCOL_ID)
				.map(|(_, msg_bytes)| WireMessage::decode(&mut msg_bytes.as_ref()))
				.collect();

			let v_messages = match v_messages {
				Err(_) => return Action::ReportPeer(remote, MALFORMED_MESSAGE_COST),
				Ok(v) => v,
			};

			let c_messages: Result<Vec<_>, _> = messages.iter()
				.filter(|(engine_id, _)| engine_id == &COLLATION_PROTOCOL_ID)
330
331
332
				.map(|(_, msg_bytes)| WireMessage::decode(&mut msg_bytes.as_ref()))
				.collect();

333
334
335
336
			match c_messages {
				Err(_) => Action::ReportPeer(remote, MALFORMED_MESSAGE_COST),
				Ok(c_messages) => if v_messages.is_empty() && c_messages.is_empty() {
					Action::Nop
337
				} else {
338
339
					Action::PeerMessages(remote, v_messages, c_messages)
				},
340
341
342
343
344
345
346
347
348
349
350
			}
		}
	}
}

fn construct_view(live_heads: &[Hash]) -> View {
	View(live_heads.iter().rev().take(MAX_VIEW_HEADS).cloned().collect())
}

async fn update_view(
	net: &mut impl Network,
351
352
	ctx: &mut impl SubsystemContext<Message = NetworkBridgeMessage>,
	live_heads: &[Hash],
353
	local_view: &mut View,
354
355
356
	validation_peers: &HashMap<PeerId, PeerData>,
	collation_peers: &HashMap<PeerId, PeerData>,
) -> SubsystemResult<()> {
357
	let new_view = construct_view(live_heads);
358
359
	if *local_view == new_view { return Ok(())  }

360
361
	*local_view = new_view.clone();

362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
	send_validation_message(
		net,
		validation_peers.keys().cloned(),
		WireMessage::ViewUpdate(new_view.clone()),
	).await?;

	send_collation_message(
		net,
		collation_peers.keys().cloned(),
		WireMessage::ViewUpdate(new_view.clone()),
	).await?;

	if let Err(e) = dispatch_validation_event_to_all(
		NetworkBridgeEvent::OurViewChange(new_view.clone()),
		ctx,
	).await {
		log::warn!(target: TARGET, "Aborting - Failure to dispatch messages to overseer");
		return Err(e)
	}

	if let Err(e) = dispatch_collation_event_to_all(
		NetworkBridgeEvent::OurViewChange(new_view.clone()),
		ctx,
	).await {
		log::warn!(target: TARGET, "Aborting - Failure to dispatch messages to overseer");
		return Err(e)
	}

	Ok(())
}

// Handle messages on a specific peer-set. The peer is expected to be connected on that
// peer-set.
async fn handle_peer_messages<M>(
	peer: PeerId,
	peers: &mut HashMap<PeerId, PeerData>,
	messages: Vec<WireMessage<M>>,
	net: &mut impl Network,
) -> SubsystemResult<Vec<NetworkBridgeEvent<M>>> {
	let peer_data = match peers.get_mut(&peer) {
		None => {
			net.report_peer(peer, UNCONNECTED_PEERSET_COST).await?;
404

405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
			return Ok(Vec::new());
		},
		Some(d) => d,
	};

	let mut outgoing_messages = Vec::with_capacity(messages.len());
	for message in messages {
		outgoing_messages.push(match message {
			WireMessage::ViewUpdate(new_view) => {
				if new_view.0.len() > MAX_VIEW_HEADS {
					net.report_peer(
						peer.clone(),
						MALFORMED_VIEW_COST,
					).await?;

					continue
				} else if new_view == peer_data.view {
					continue
				} else {
					peer_data.view = new_view;
425

426
427
428
429
430
431
432
433
434
435
436
					NetworkBridgeEvent::PeerViewChange(
						peer.clone(),
						peer_data.view.clone(),
					)
				}
			}
			WireMessage::ProtocolMessage(message) => {
				NetworkBridgeEvent::PeerMessage(peer.clone(), message)
			}
		})
	}
437

438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
	Ok(outgoing_messages)
}

async fn send_validation_message<I>(
	net: &mut impl Network,
	peers: I,
	message: WireMessage<protocol_v1::ValidationProtocol>,
) -> SubsystemResult<()>
	where
		I: IntoIterator<Item=PeerId>,
		I::IntoIter: ExactSizeIterator,
{
	send_message(net, peers, PeerSet::Validation, message).await
}

async fn send_collation_message<I>(
	net: &mut impl Network,
	peers: I,
	message: WireMessage<protocol_v1::CollationProtocol>,
) -> SubsystemResult<()>
	where
	I: IntoIterator<Item=PeerId>,
	I::IntoIter: ExactSizeIterator,
{
	send_message(net, peers, PeerSet::Collation, message).await
}

async fn send_message<M, I>(
	net: &mut impl Network,
	peers: I,
	peer_set: PeerSet,
	message: WireMessage<M>,
) -> SubsystemResult<()>
	where
		M: Encode + Clone,
		I: IntoIterator<Item=PeerId>,
		I::IntoIter: ExactSizeIterator,
{
	let mut message_producer = stream::iter({
		let peers = peers.into_iter();
		let n_peers = peers.len();
		let mut message = Some(message.encode());

		peers.enumerate().map(move |(i, peer)| {
			// optimization: avoid cloning the message for the last peer in the
			// list. The message payload can be quite large. If the underlying
			// network used `Bytes` this would not be necessary.
			let message = if i == n_peers - 1 {
				message.take()
					.expect("Only taken in last iteration of loop, never afterwards; qed")
			} else {
				message.as_ref()
					.expect("Only taken in last iteration of loop, we are not there yet; qed")
					.clone()
			};

			Ok(NetworkAction::WriteNotification(peer, peer_set, message))
		})
	});

	net.action_sink().send_all(&mut message_producer).await
}

async fn dispatch_validation_event_to_all(
	event: NetworkBridgeEvent<protocol_v1::ValidationProtocol>,
	ctx: &mut impl SubsystemContext<Message=NetworkBridgeMessage>,
) -> SubsystemResult<()> {
	dispatch_validation_events_to_all(std::iter::once(event), ctx).await
}

async fn dispatch_collation_event_to_all(
	event: NetworkBridgeEvent<protocol_v1::CollationProtocol>,
	ctx: &mut impl SubsystemContext<Message=NetworkBridgeMessage>,
) -> SubsystemResult<()> {
	dispatch_collation_events_to_all(std::iter::once(event), ctx).await
}

async fn dispatch_validation_events_to_all<I>(
	events: I,
	ctx: &mut impl SubsystemContext<Message=NetworkBridgeMessage>,
) -> SubsystemResult<()>
	where
		I: IntoIterator<Item = NetworkBridgeEvent<protocol_v1::ValidationProtocol>>,
		I::IntoIter: Send,
{
	let messages_for = |event: NetworkBridgeEvent<protocol_v1::ValidationProtocol>| {
		let a = std::iter::once(event.focus().ok().map(|m| AllMessages::AvailabilityDistribution(
			AvailabilityDistributionMessage::NetworkBridgeUpdateV1(m)
		)));

		let b = std::iter::once(event.focus().ok().map(|m| AllMessages::BitfieldDistribution(
			BitfieldDistributionMessage::NetworkBridgeUpdateV1(m)
		)));

		let p = std::iter::once(event.focus().ok().map(|m| AllMessages::PoVDistribution(
			PoVDistributionMessage::NetworkBridgeUpdateV1(m)
		)));

		let s = std::iter::once(event.focus().ok().map(|m| AllMessages::StatementDistribution(
			StatementDistributionMessage::NetworkBridgeUpdateV1(m)
		)));

		a.chain(b).chain(p).chain(s).filter_map(|x| x)
	};

	ctx.send_messages(events.into_iter().flat_map(messages_for)).await
}

async fn dispatch_collation_events_to_all<I>(
	events: I,
	ctx: &mut impl SubsystemContext<Message=NetworkBridgeMessage>,
) -> SubsystemResult<()>
	where
		I: IntoIterator<Item = NetworkBridgeEvent<protocol_v1::CollationProtocol>>,
		I::IntoIter: Send,
{
	let messages_for = |event: NetworkBridgeEvent<protocol_v1::CollationProtocol>| {
		event.focus().ok().map(|m| AllMessages::CollatorProtocol(
			CollatorProtocolMessage::NetworkBridgeUpdateV1(m)
		))
	};

	ctx.send_messages(events.into_iter().flat_map(messages_for)).await
561
562
}

563
564
565
async fn run_network<N, AD>(
	mut network_service: N,
	mut authority_discovery_service: AD,
566
	mut ctx: impl SubsystemContext<Message=NetworkBridgeMessage>,
567
568
569
570
571
572
) -> SubsystemResult<()>
where
	N: Network + validator_discovery::Network,
	AD: validator_discovery::AuthorityDiscovery,
{
	let mut event_stream = network_service.event_stream().fuse();
573
574

	// Most recent heads are at the back.
575
	let mut live_heads: Vec<Hash> = Vec::with_capacity(MAX_VIEW_HEADS);
576
577
	let mut local_view = View(Vec::new());

578
579
	let mut validation_peers: HashMap<PeerId, PeerData> = HashMap::new();
	let mut collation_peers: HashMap<PeerId, PeerData> = HashMap::new();
580

581
582
	let mut validator_discovery = validator_discovery::Service::<N, AD>::new();

583
	loop {
584

585
586
587
588
589
		let action = {
			let subsystem_next = ctx.recv().fuse();
			let mut net_event_next = event_stream.next().fuse();
			futures::pin_mut!(subsystem_next);

590
591
			futures::select! {
				subsystem_msg = subsystem_next => action_from_overseer_message(subsystem_msg),
592
593
594
595
596
				net_event = net_event_next => action_from_network_message(net_event),
			}
		};

		match action {
597
598
			Action::Nop => {}
			Action::Abort => return Ok(()),
599

600
			Action::SendValidationMessage(peers, msg) => send_message(
601
					&mut network_service,
602
603
604
605
606
607
					peers,
					PeerSet::Validation,
					WireMessage::ProtocolMessage(msg),
			).await?,

			Action::SendCollationMessage(peers, msg) => send_message(
608
					&mut network_service,
609
610
611
612
613
					peers,
					PeerSet::Collation,
					WireMessage::ProtocolMessage(msg),
			).await?,

614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
			Action::ConnectToValidators {
				validator_ids,
				connected,
				revoke,
			} => {
				let (ns, ads) = validator_discovery.on_request(
					validator_ids,
					connected,
					revoke,
					network_service,
					authority_discovery_service,
				).await;
				network_service = ns;
				authority_discovery_service = ads;
			},
629

630
			Action::ReportPeer(peer, rep) => network_service.report_peer(peer, rep).await?,
631

632
633
634
635
			Action::ActiveLeaves(ActiveLeavesUpdate { activated, deactivated }) => {
				live_heads.extend(activated);
				live_heads.retain(|h| !deactivated.contains(h));

636
				update_view(
637
					&mut network_service,
638
639
640
641
642
643
					&mut ctx,
					&live_heads,
					&mut local_view,
					&validation_peers,
					&collation_peers,
				).await?;
644
			}
645
646
647
648
649
650
651

			Action::PeerConnected(peer_set, peer, role) => {
				let peer_map = match peer_set {
					PeerSet::Validation => &mut validation_peers,
					PeerSet::Collation => &mut collation_peers,
				};

652
653
				validator_discovery.on_peer_connected(&peer, &mut authority_discovery_service).await;

654
				match peer_map.entry(peer.clone()) {
655
656
					hash_map::Entry::Occupied(_) => continue,
					hash_map::Entry::Vacant(vacant) => {
657
658
659
660
						vacant.insert(PeerData {
							view: View(Vec::new()),
						});

661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
						let res = match peer_set {
							PeerSet::Validation => dispatch_validation_events_to_all(
								vec![
									NetworkBridgeEvent::PeerConnected(peer.clone(), role),
									NetworkBridgeEvent::PeerViewChange(
										peer,
										View(Default::default()),
									),
								],
								&mut ctx,
							).await,
							PeerSet::Collation => dispatch_collation_events_to_all(
								vec![
									NetworkBridgeEvent::PeerConnected(peer.clone(), role),
									NetworkBridgeEvent::PeerViewChange(
										peer,
										View(Default::default()),
									),
								],
								&mut ctx,
							).await,
						};

						if let Err(e) = res {
685
							log::warn!("Aborting - Failure to dispatch messages to overseer");
686
							return Err(e);
687
688
689
690
						}
					}
				}
			}
691
692
693
694
695
696
			Action::PeerDisconnected(peer_set, peer) => {
				let peer_map = match peer_set {
					PeerSet::Validation => &mut validation_peers,
					PeerSet::Collation => &mut collation_peers,
				};

697
698
				validator_discovery.on_peer_disconnected(&peer, &mut authority_discovery_service).await;

699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
				if peer_map.remove(&peer).is_some() {
					let res = match peer_set {
						PeerSet::Validation => dispatch_validation_event_to_all(
							NetworkBridgeEvent::PeerDisconnected(peer),
							&mut ctx,
						).await,
						PeerSet::Collation => dispatch_collation_event_to_all(
							NetworkBridgeEvent::PeerDisconnected(peer),
							&mut ctx,
						).await,
					};

					if let Err(e) = res {
						log::warn!(
							target: TARGET,
							"Aborting - Failure to dispatch messages to overseer",
						);
716
717
718
719
						return Err(e)
					}
				}
			},
720
721
722
723
724
725
			Action::PeerMessages(peer, v_messages, c_messages) => {
				if !v_messages.is_empty() {
					let events = handle_peer_messages(
						peer.clone(),
						&mut validation_peers,
						v_messages,
726
						&mut network_service,
727
728
729
730
731
732
733
734
735
736
737
					).await?;

					if let Err(e) = dispatch_validation_events_to_all(
						events,
						&mut ctx,
					).await {
						log::warn!(
							target: TARGET,
							"Aborting - Failure to dispatch messages to overseer",
						);
						return Err(e)
738
739
740
					}
				}

741
742
743
744
745
				if !c_messages.is_empty() {
					let events = handle_peer_messages(
						peer.clone(),
						&mut collation_peers,
						c_messages,
746
						&mut network_service,
747
748
749
750
751
752
753
754
755
756
757
758
					).await?;

					if let Err(e) = dispatch_collation_events_to_all(
						events,
						&mut ctx,
					).await {
						log::warn!(
							target: TARGET,
							"Aborting - Failure to dispatch messages to overseer",
						);
						return Err(e)
					}
759
760
761
762
763
764
				}
			},
		}
	}
}

765

766
767
768
769
#[cfg(test)]
mod tests {
	use super::*;
	use futures::channel::mpsc;
770
	use futures::executor;
771
772

	use std::sync::Arc;
773
774
	use std::collections::HashSet;
	use async_trait::async_trait;
775
776
777
778
	use parking_lot::Mutex;
	use assert_matches::assert_matches;

	use polkadot_subsystem::messages::{StatementDistributionMessage, BitfieldDistributionMessage};
779
780
781
	use polkadot_node_subsystem_test_helpers::{
		SingleItemSink, SingleItemStream, TestSubsystemContextHandle,
	};
782
	use sc_network::Multiaddr;
783
	use sp_keyring::Sr25519Keyring;
784
785
786
787
788
789
790

	// The subsystem's view of the network - only supports a single call to `event_stream`.
	struct TestNetwork {
		net_events: Arc<Mutex<Option<SingleItemStream<NetworkEvent>>>>,
		action_tx: mpsc::UnboundedSender<NetworkAction>,
	}

791
792
	struct TestAuthorityDiscovery;

793
794
795
796
797
798
799
800
801
802
	// The test's view of the network. This receives updates from the subsystem in the form
	// of `NetworkAction`s.
	struct TestNetworkHandle {
		action_rx: mpsc::UnboundedReceiver<NetworkAction>,
		net_tx: SingleItemSink<NetworkEvent>,
	}

	fn new_test_network() -> (
		TestNetwork,
		TestNetworkHandle,
803
		TestAuthorityDiscovery,
804
	) {
805
		let (net_tx, net_rx) = polkadot_node_subsystem_test_helpers::single_item_sink();
806
807
808
809
810
811
812
813
814
815
816
		let (action_tx, action_rx) = mpsc::unbounded();

		(
			TestNetwork {
				net_events: Arc::new(Mutex::new(Some(net_rx))),
				action_tx,
			},
			TestNetworkHandle {
				action_rx,
				net_tx,
			},
817
			TestAuthorityDiscovery,
818
819
820
		)
	}

821
822
823
824
825
826
827
	fn peer_set_engine_id(peer_set: PeerSet) -> ConsensusEngineId {
		match peer_set {
			PeerSet::Validation => VALIDATION_PROTOCOL_ID,
			PeerSet::Collation => COLLATION_PROTOCOL_ID,
		}
	}

828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
	impl Network for TestNetwork {
		fn event_stream(&mut self) -> BoxStream<'static, NetworkEvent> {
			self.net_events.lock()
				.take()
				.expect("Subsystem made more than one call to `event_stream`")
				.boxed()
		}

		fn action_sink<'a>(&'a mut self)
			-> Pin<Box<dyn Sink<NetworkAction, Error = SubsystemError> + Send + 'a>>
		{
			Box::pin((&mut self.action_tx).sink_map_err(Into::into))
		}
	}

843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
	impl validator_discovery::Network for TestNetwork {
		fn set_priority_group(&self, _group_id: String, _multiaddresses: HashSet<Multiaddr>) -> Result<(), String> {
			Ok(())
		}
	}

	#[async_trait]
	impl validator_discovery::AuthorityDiscovery for TestAuthorityDiscovery {
		async fn get_addresses_by_authority_id(&mut self, _authority: AuthorityDiscoveryId) -> Option<Vec<Multiaddr>> {
			None
		}

		async fn get_authority_id_by_peer_id(&mut self, _peer_id: PeerId) -> Option<AuthorityDiscoveryId> {
			None
		}
	}

860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
	impl TestNetworkHandle {
		// Get the next network action.
		async fn next_network_action(&mut self) -> NetworkAction {
			self.action_rx.next().await.expect("subsystem concluded early")
		}

		// Wait for the next N network actions.
		async fn next_network_actions(&mut self, n: usize) -> Vec<NetworkAction> {
			let mut v = Vec::with_capacity(n);
			for _ in 0..n {
				v.push(self.next_network_action().await);
			}

			v
		}

876
		async fn connect_peer(&mut self, peer: PeerId, peer_set: PeerSet, role: ObservedRole) {
877
878
			self.send_network_event(NetworkEvent::NotificationStreamOpened {
				remote: peer,
879
880
				engine_id: peer_set_engine_id(peer_set),
				role: role.into(),
881
882
883
			}).await;
		}

884
		async fn disconnect_peer(&mut self, peer: PeerId, peer_set: PeerSet) {
885
886
			self.send_network_event(NetworkEvent::NotificationStreamClosed {
				remote: peer,
887
				engine_id: peer_set_engine_id(peer_set),
888
889
890
			}).await;
		}

891
		async fn peer_message(&mut self, peer: PeerId, peer_set: PeerSet, message: Vec<u8>) {
892
893
			self.send_network_event(NetworkEvent::NotificationsReceived {
				remote: peer,
894
				messages: vec![(peer_set_engine_id(peer_set), message.into())],
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
			}).await;
		}

		async fn send_network_event(&mut self, event: NetworkEvent) {
			self.net_tx.send(event).await.expect("subsystem concluded early");
		}
	}

	// network actions are sensitive to ordering of `PeerId`s within a `HashMap`, so
	// we need to use this to prevent fragile reliance on peer ordering.
	fn network_actions_contains(actions: &[NetworkAction], action: &NetworkAction) -> bool {
		actions.iter().find(|&x| x == action).is_some()
	}

	struct TestHarness {
		network_handle: TestNetworkHandle,
911
		virtual_overseer: TestSubsystemContextHandle<NetworkBridgeMessage>,
912
913
914
	}

	fn test_harness<T: Future<Output=()>>(test: impl FnOnce(TestHarness) -> T) {
Bastian Köcher's avatar
Bastian Köcher committed
915
		let pool = sp_core::testing::TaskExecutor::new();
916
		let (network, network_handle, discovery) = new_test_network();
917
		let (context, virtual_overseer) = polkadot_node_subsystem_test_helpers::make_subsystem_context(pool);
918
919
920

		let network_bridge = run_network(
			network,
921
			discovery,
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
			context,
		)
			.map_err(|_| panic!("subsystem execution failed"))
			.map(|_| ());

		let test_fut = test(TestHarness {
			network_handle,
			virtual_overseer,
		});

		futures::pin_mut!(test_fut);
		futures::pin_mut!(network_bridge);

		executor::block_on(future::select(test_fut, network_bridge));
	}

938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
	async fn assert_sends_validation_event_to_all(
		event: NetworkBridgeEvent<protocol_v1::ValidationProtocol>,
		virtual_overseer: &mut TestSubsystemContextHandle<NetworkBridgeMessage>,
	) {
		assert_matches!(
			virtual_overseer.recv().await,
			AllMessages::AvailabilityDistribution(
				AvailabilityDistributionMessage::NetworkBridgeUpdateV1(e)
			) if e == event.focus().expect("could not focus message")
		);

		assert_matches!(
			virtual_overseer.recv().await,
			AllMessages::BitfieldDistribution(
				BitfieldDistributionMessage::NetworkBridgeUpdateV1(e)
			) if e == event.focus().expect("could not focus message")
		);

		assert_matches!(
			virtual_overseer.recv().await,
			AllMessages::PoVDistribution(
				PoVDistributionMessage::NetworkBridgeUpdateV1(e)
			) if e == event.focus().expect("could not focus message")
		);

		assert_matches!(
			virtual_overseer.recv().await,
			AllMessages::StatementDistribution(
				StatementDistributionMessage::NetworkBridgeUpdateV1(e)
			) if e == event.focus().expect("could not focus message")
		);
	}

	async fn assert_sends_collation_event_to_all(
		event: NetworkBridgeEvent<protocol_v1::CollationProtocol>,
		virtual_overseer: &mut TestSubsystemContextHandle<NetworkBridgeMessage>,
	) {
		assert_matches!(
			virtual_overseer.recv().await,
			AllMessages::CollatorProtocol(
				CollatorProtocolMessage::NetworkBridgeUpdateV1(e)
			) if e == event.focus().expect("could not focus message")
		)
	}

983
984
985
986
987
988
989
990
	#[test]
	fn sends_view_updates_to_peers() {
		test_harness(|test_harness| async move {
			let TestHarness { mut network_handle, mut virtual_overseer } = test_harness;

			let peer_a = PeerId::random();
			let peer_b = PeerId::random();

991
992
993
994
995
996
997
998
999
1000
			network_handle.connect_peer(
				peer_a.clone(),
				PeerSet::Validation,
				ObservedRole::Full,
			).await;
			network_handle.connect_peer(
				peer_b.clone(),
				PeerSet::Validation,
				ObservedRole::Full,
			).await;
For faster browsing, not all history is shown. View entire blame