network.rs 7.28 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Copyright 2020-2021 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
18
use std::borrow::Cow;
use std::collections::HashSet;
19
20
use std::sync::Arc;

21
use async_trait::async_trait;
22
23
24
25
26
27
use futures::prelude::*;
use futures::stream::BoxStream;

use parity_scale_codec::Encode;

use sc_network::Event as NetworkEvent;
28
use sc_network::{IfDisconnected, NetworkService, OutboundFailure, RequestFailure};
29
use sc_network::{config::parse_addr, multiaddr::Multiaddr};
30

31
32
use polkadot_node_network_protocol::{
	peer_set::PeerSet,
33
	request_response::{OutgoingRequest, Requests, Recipient},
34
	PeerId, UnifiedReputationChange as Rep,
35
};
36
use polkadot_primitives::v1::{AuthorityDiscoveryId, Block, Hash};
37

38
use crate::validator_discovery::AuthorityDiscovery;
39

40
41
use super::LOG_TARGET;

42
43
44
45
46
/// Send a message to the network.
///
/// This function is only used internally by the network-bridge, which is responsible to only send
/// messages that are compatible with the passed peer set, as that is currently not enforced by
/// this function. These are messages of type `WireMessage` parameterized on the matching type.
47
pub(crate) fn send_message<M>(
48
	net: &mut impl Network,
49
	mut peers: Vec<PeerId>,
50
51
	peer_set: PeerSet,
	message: M,
52
	metrics: &super::Metrics,
53
)
54
55
56
where
	M: Encode + Clone,
{
57
58
59
60
61
62
63
64
65
66
67
68
	let message = {
		let encoded = message.encode();
		metrics.on_notification_sent(peer_set, encoded.len(), peers.len());
		encoded
	};

	// 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 last_peer = peers.pop();
	peers.into_iter().for_each(|peer| {
		net.write_notification(peer, peer_set, message.clone());
69
	});
70
71
72
	if let Some(peer) = last_peer {
		net.write_notification(peer, peer_set, message);
	}
73
74
75
}

/// An abstraction over networking for the purposes of this subsystem.
76
#[async_trait]
77
pub trait Network: Clone + Send + 'static {
78
79
80
81
82
83
	/// 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
	/// to the [`VALIDATION_PROTOCOL_NAME`](VALIDATION_PROTOCOL_NAME)
	/// or [`COLLATION_PROTOCOL_NAME`](COLLATION_PROTOCOL_NAME)
	fn event_stream(&mut self) -> BoxStream<'static, NetworkEvent>;

84
85
86
	/// Ask the network to keep a substream open with these nodes and not disconnect from them
	/// until removed from the protocol's peer set.
	/// Note that `out_peers` setting has no effect on this.
87
88
89
90
91
	async fn add_to_peers_set(
		&mut self,
		protocol: Cow<'static, str>,
		multiaddresses: HashSet<Multiaddr>,
	) -> Result<(), String>;
92

93
94
95
96
97
98
	/// Cancels the effects of `add_to_peers_set`.
	async fn remove_from_peers_set(
		&mut self,
		protocol: Cow<'static, str>,
		multiaddresses: HashSet<Multiaddr>,
	) -> Result<(), String>;
99

100
	/// Send a request to a remote peer.
101
102
103
104
	async fn start_request<AD: AuthorityDiscovery>(
		&self,
		authority_discovery: &mut AD,
		req: Requests,
105
		if_disconnected: IfDisconnected,
106
	);
107

108
	/// Report a given peer as either beneficial (+) or costly (-) according to the given scalar.
109
	fn report_peer(&self, who: PeerId, cost_benefit: Rep);
110

111
	/// Disconnect a given peer from the peer set specified without harming reputation.
112
	fn disconnect_peer(&self, who: PeerId, peer_set: PeerSet);
113

114
115
	/// Write a notification to a peer on the given peer-set's protocol.
	fn write_notification(
116
		&self,
117
118
119
		who: PeerId,
		peer_set: PeerSet,
		message: Vec<u8>,
120
	);
121
122
}

123
#[async_trait]
124
impl Network for Arc<NetworkService<Block, Hash>> {
125
	fn event_stream(&mut self) -> BoxStream<'static, NetworkEvent> {
126
		NetworkService::event_stream(self, "polkadot-network-bridge").boxed()
127
128
	}

129
130
131
132
133
	async fn add_to_peers_set(
		&mut self,
		protocol: Cow<'static, str>,
		multiaddresses: HashSet<Multiaddr>,
	) -> Result<(), String> {
134
135
136
		sc_network::NetworkService::add_peers_to_reserved_set(&**self, protocol, multiaddresses)
	}

137
138
139
140
141
142
143
144
145
146
	async fn remove_from_peers_set(
		&mut self,
		protocol: Cow<'static, str>,
		multiaddresses: HashSet<Multiaddr>,
	) -> Result<(), String> {
		sc_network::NetworkService::remove_peers_from_reserved_set(
			&**self,
			protocol.clone(),
			multiaddresses.clone(),
		)?;
147
148
149
		sc_network::NetworkService::remove_from_peers_set(&**self, protocol, multiaddresses)
	}

150
151
152
	fn report_peer(&self, who: PeerId, cost_benefit: Rep) {
		sc_network::NetworkService::report_peer(&**self, who, cost_benefit.into_base_rep());
	}
153

154
155
156
	fn disconnect_peer(&self, who: PeerId, peer_set: PeerSet) {
		sc_network::NetworkService::disconnect_peer(&**self, who, peer_set.into_protocol_name());
	}
157

158
159
160
161
162
163
164
	fn write_notification(&self, who: PeerId, peer_set: PeerSet, message: Vec<u8>) {
		sc_network::NetworkService::write_notification(
			&**self,
			who,
			peer_set.into_protocol_name(),
			message,
		);
165
	}
166

167
168
169
170
	async fn start_request<AD: AuthorityDiscovery>(
		&self,
		authority_discovery: &mut AD,
		req: Requests,
171
		if_disconnected: IfDisconnected,
172
	) {
173
174
175
176
177
178
179
180
181
		let (
			protocol,
			OutgoingRequest {
				peer,
				payload,
				pending_response,
			},
		) = req.encode_request();

182
183
		let peer_id = match peer {
			Recipient::Peer(peer_id) =>  Some(peer_id),
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
			Recipient::Authority(authority) => {
				let mut found_peer_id = None;
				// Note: `get_addresses_by_authority_id` searched in a cache, and it thus expected
				// to be very quick.
				for addr in authority_discovery
					.get_addresses_by_authority_id(authority).await
					.into_iter().flat_map(|list| list.into_iter())
				{
					let (peer_id, addr) = match parse_addr(addr) {
						Ok(v) => v,
						Err(_) => continue,
					};
					NetworkService::add_known_address(
						&*self,
						peer_id.clone(),
						addr,
					);
					found_peer_id = Some(peer_id);
				}
				found_peer_id
			}
205
		};
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226

		let peer_id = match peer_id {
			None => {
				tracing::debug!(target: LOG_TARGET, "Discovering authority failed");
				match pending_response
					.send(Err(RequestFailure::Network(OutboundFailure::DialFailure)))
				{
					Err(_) => tracing::debug!(
						target: LOG_TARGET,
						"Sending failed request response failed."
					),
					Ok(_) => {}
				}
				return;
			}
			Some(peer_id) => peer_id,
		};

		NetworkService::start_request(
			&*self,
			peer_id,
227
228
229
			protocol.into_protocol_name(),
			payload,
			pending_response,
230
			if_disconnected,
231
232
		);
	}
233
}
234
235
236
237
238
239
240
241
242
243
244
245
246
247

/// We assume one peer_id per authority_id.
pub async fn get_peer_id_by_authority_id<AD: AuthorityDiscovery>(
	authority_discovery: &mut AD,
	authority: AuthorityDiscoveryId,
) -> Option<PeerId> {
	// Note: `get_addresses_by_authority_id` searched in a cache, and it thus expected
	// to be very quick.
	authority_discovery
		.get_addresses_by_authority_id(authority).await
		.into_iter()
		.flat_map(|list| list.into_iter())
		.find_map(|addr| parse_addr(addr).ok().map(|(p, _)| p))
}