referrerpolicy=no-referrer-when-downgrade
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Copyright (C) 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/>.

//! Mocked `network-bridge` subsystems that uses a `NetworkInterface` to access
//! the emulated network.

use crate::{
	configuration::TestAuthorities,
	network::{NetworkEmulatorHandle, NetworkInterfaceReceiver, NetworkMessage, RequestExt},
};
use futures::{channel::mpsc::UnboundedSender, FutureExt, StreamExt};
use polkadot_node_network_protocol::Versioned;
use polkadot_node_subsystem::{
	messages::{
		ApprovalDistributionMessage, ApprovalVotingParallelMessage, NetworkBridgeTxMessage,
	},
	overseer, SpawnedSubsystem, SubsystemError,
};
use polkadot_node_subsystem_types::{
	messages::{BitfieldDistributionMessage, NetworkBridgeEvent, StatementDistributionMessage},
	OverseerSignal,
};
use sc_network::{request_responses::ProtocolConfig, RequestFailure};

const LOG_TARGET: &str = "subsystem-bench::network-bridge";
const ALLOWED_PROTOCOLS: &[&str] = &[
	"/ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff/req_chunk/2",
	"/ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff/req_attested_candidate/2",
];

/// A mock of the network bridge tx subsystem.
pub struct MockNetworkBridgeTx {
	/// A network emulator handle
	network: NetworkEmulatorHandle,
	/// A channel to the network interface,
	to_network_interface: UnboundedSender<NetworkMessage>,
	/// Test authorities
	test_authorities: TestAuthorities,
}

/// A mock of the network bridge tx subsystem.
pub struct MockNetworkBridgeRx {
	/// A network interface receiver
	network_receiver: NetworkInterfaceReceiver,
	/// Chunk request sender
	chunk_request_sender: Option<ProtocolConfig>,
	/// Approval voting parallel enabled.
	approval_voting_parallel_enabled: bool,
}

impl MockNetworkBridgeTx {
	pub fn new(
		network: NetworkEmulatorHandle,
		to_network_interface: UnboundedSender<NetworkMessage>,
		test_authorities: TestAuthorities,
	) -> MockNetworkBridgeTx {
		Self { network, to_network_interface, test_authorities }
	}
}

impl MockNetworkBridgeRx {
	pub fn new(
		network_receiver: NetworkInterfaceReceiver,
		chunk_request_sender: Option<ProtocolConfig>,
		approval_voting_parallel_enabled: bool,
	) -> MockNetworkBridgeRx {
		Self { network_receiver, chunk_request_sender, approval_voting_parallel_enabled }
	}
}

#[overseer::subsystem(NetworkBridgeTx, error=SubsystemError, prefix=self::overseer)]
impl<Context> MockNetworkBridgeTx {
	fn start(self, ctx: Context) -> SpawnedSubsystem {
		let future = self.run(ctx).map(|_| Ok(())).boxed();

		SpawnedSubsystem { name: "network-bridge-tx", future }
	}
}

#[overseer::subsystem(NetworkBridgeRx, error=SubsystemError, prefix=self::overseer)]
impl<Context> MockNetworkBridgeRx {
	fn start(self, ctx: Context) -> SpawnedSubsystem {
		let future = self.run(ctx).map(|_| Ok(())).boxed();

		SpawnedSubsystem { name: "network-bridge-rx", future }
	}
}

#[overseer::contextbounds(NetworkBridgeTx, prefix = self::overseer)]
impl MockNetworkBridgeTx {
	async fn run<Context>(self, mut ctx: Context) {
		// Main subsystem loop.
		loop {
			let subsystem_message = ctx.recv().await.expect("Overseer never fails us");
			match subsystem_message {
				orchestra::FromOrchestra::Signal(signal) =>
					if signal == OverseerSignal::Conclude {
						return
					},
				orchestra::FromOrchestra::Communication { msg } => match msg {
					NetworkBridgeTxMessage::SendRequests(requests, _if_disconnected) => {
						for request in requests {
							gum::debug!(target: LOG_TARGET, request = ?request, "Processing request");
							let peer_id = match request.authority_id() {
								Some(v) => v.clone(),
								None => self
									.test_authorities
									.peer_id_to_authority
									.get(request.peer_id().expect("Should exist"))
									.expect("Should exist")
									.clone(),
							};

							if !self.network.is_peer_connected(&peer_id) {
								// Attempting to send a request to a disconnected peer.
								request
									.into_response_sender()
									.send(Err(RequestFailure::NotConnected))
									.expect("send never fails");
								continue
							}

							let peer_message =
								NetworkMessage::RequestFromNode(peer_id.clone(), request);

							let _ = self.to_network_interface.unbounded_send(peer_message);
						}
					},
					NetworkBridgeTxMessage::ReportPeer(_) => {
						// ignore rep changes
					},
					NetworkBridgeTxMessage::SendValidationMessage(peers, message) => {
						for peer in peers {
							self.to_network_interface
								.unbounded_send(NetworkMessage::MessageFromNode(
									self.test_authorities
										.peer_id_to_authority
										.get(&peer)
										.unwrap()
										.clone(),
									message.clone(),
								))
								.expect("Should not fail");
						}
					},
					NetworkBridgeTxMessage::SendValidationMessages(messages) => {
						for (peers, message) in messages {
							for peer in peers {
								self.to_network_interface
									.unbounded_send(NetworkMessage::MessageFromNode(
										self.test_authorities
											.peer_id_to_authority
											.get(&peer)
											.unwrap()
											.clone(),
										message.clone(),
									))
									.expect("Should not fail");
							}
						}
					},
					message => unimplemented!("Unexpected network bridge message {:?}", message),
				},
			}
		}
	}
}

#[overseer::contextbounds(NetworkBridgeRx, prefix = self::overseer)]
impl MockNetworkBridgeRx {
	async fn run<Context>(mut self, mut ctx: Context) {
		// Main subsystem loop.
		let mut from_network_interface = self.network_receiver.0;
		loop {
			futures::select! {
				maybe_peer_message = from_network_interface.next() => {
					if let Some(message) = maybe_peer_message {
						match message {
							NetworkMessage::MessageFromPeer(peer_id, message) => match message {
								Versioned::V2(
									polkadot_node_network_protocol::v2::ValidationProtocol::BitfieldDistribution(
										bitfield,
									),
								) => {
									ctx.send_message(
										BitfieldDistributionMessage::NetworkBridgeUpdate(NetworkBridgeEvent::PeerMessage(peer_id, polkadot_node_network_protocol::Versioned::V2(bitfield)))
									).await;
								},
								Versioned::V3(
									polkadot_node_network_protocol::v3::ValidationProtocol::ApprovalDistribution(msg)
								) => {
									if self.approval_voting_parallel_enabled {
										ctx.send_message(
											ApprovalVotingParallelMessage::NetworkBridgeUpdate(NetworkBridgeEvent::PeerMessage(peer_id, polkadot_node_network_protocol::Versioned::V3(msg)))
										).await;
									} else {
										ctx.send_message(
											ApprovalDistributionMessage::NetworkBridgeUpdate(NetworkBridgeEvent::PeerMessage(peer_id, polkadot_node_network_protocol::Versioned::V3(msg)))
										).await;
									}
								}
								Versioned::V3(
									polkadot_node_network_protocol::v3::ValidationProtocol::StatementDistribution(msg)
								) => {
									ctx.send_message(
										StatementDistributionMessage::NetworkBridgeUpdate(NetworkBridgeEvent::PeerMessage(peer_id, polkadot_node_network_protocol::Versioned::V3(msg)))
									).await;
								}
								_ => {
									unimplemented!("We only talk v2 network protocol")
								},
							},
							NetworkMessage::RequestFromPeer(request) => {
								if let Some(protocol) = self.chunk_request_sender.as_mut() {
									assert!(ALLOWED_PROTOCOLS.contains(&&*protocol.name));
									if let Some(inbound_queue) = protocol.inbound_queue.as_ref() {
										inbound_queue
											.send(request)
											.await
											.expect("Forwarding requests to subsystem never fails");
									}
								}
							},
							_ => {
								panic!("NetworkMessage::RequestFromNode is not expected to be received from a peer")
							}
						}
					}
				},
				subsystem_message = ctx.recv().fuse() => {
					match subsystem_message.expect("Overseer never fails us") {
						orchestra::FromOrchestra::Signal(signal) => if signal == OverseerSignal::Conclude { return },
						_ => {
							unimplemented!("Unexpected network bridge rx message")
						},
					}
				}
			}
		}
	}
}