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

//! Network protocol types for parachains.

19
#![deny(unused_crate_dependencies)]
20
21
#![warn(missing_docs)]

22
use polkadot_primitives::v1::{Hash, BlockNumber};
23
use parity_scale_codec::{Encode, Decode};
24
use std::{fmt, collections::HashMap};
25

26
pub use sc_network::PeerId;
27
#[doc(hidden)]
28
pub use polkadot_node_jaeger as jaeger;
29
30
#[doc(hidden)]
pub use std::sync::Arc;
31

32
33
mod reputation;
pub use self::reputation::{ReputationChange, UnifiedReputationChange};
34
35
36
37

/// Peer-sets and protocols used for parachains.
pub mod peer_set;

38
39
40
/// Request/response protocols used in Polkadot.
pub mod request_response;

41
42
43
44
45
46
47
48
49
50
/// A unique identifier of a request.
pub type RequestId = u64;

/// A version of the protocol.
pub type ProtocolVersion = u32;

/// An error indicating that this the over-arching message type had the wrong variant
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct WrongVariant;

51
52
53
54
55
56
57
58
impl fmt::Display for WrongVariant {
	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(formatter, "Wrong message variant")
	}
}

impl std::error::Error for WrongVariant {}

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/// The advertised role of a node.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ObservedRole {
	/// A light node.
	Light,
	/// A full node.
	Full,
	/// A node claiming to be an authority (unauthenticated)
	Authority,
}

impl From<sc_network::ObservedRole> for ObservedRole {
	fn from(role: sc_network::ObservedRole) -> ObservedRole {
		match role {
			sc_network::ObservedRole::Light => ObservedRole::Light,
			sc_network::ObservedRole::Authority => ObservedRole::Authority,
75
			sc_network::ObservedRole::Full => ObservedRole::Full,
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
		}
	}
}

impl Into<sc_network::ObservedRole> for ObservedRole {
	fn into(self) -> sc_network::ObservedRole {
		match self {
			ObservedRole::Light => sc_network::ObservedRole::Light,
			ObservedRole::Full => sc_network::ObservedRole::Full,
			ObservedRole::Authority => sc_network::ObservedRole::Authority,
		}
	}
}

macro_rules! impl_try_from {
	($m_ty:ident, $variant:ident, $out:ty) => {
		impl TryFrom<$m_ty> for $out {
			type Error = crate::WrongVariant;

			#[allow(unreachable_patterns)] // when there is only one variant
			fn try_from(x: $m_ty) -> Result<$out, Self::Error> {
				match x {
					$m_ty::$variant(y) => Ok(y),
					_ => Err(crate::WrongVariant),
				}
			}
		}

		impl<'a> TryFrom<&'a $m_ty> for &'a $out {
			type Error = crate::WrongVariant;

			fn try_from(x: &'a $m_ty) -> Result<&'a $out, Self::Error> {
				#[allow(unreachable_patterns)] // when there is only one variant
				match *x {
					$m_ty::$variant(ref y) => Ok(y),
					_ => Err(crate::WrongVariant),
				}
			}
		}
	}
}


119
120
/// Specialized wrapper around [`View`].
///
121
/// Besides the access to the view itself, it also gives access to the [`jaeger::Span`] per leave/head.
122
123
124
#[derive(Debug, Clone, Default)]
pub struct OurView {
	view: View,
125
	span_per_head: HashMap<Hash, Arc<jaeger::Span>>,
126
127
128
129
}

impl OurView {
	/// Creates a new instance.
130
	pub fn new(heads: impl IntoIterator<Item = (Hash, Arc<jaeger::Span>)>, finalized_number: BlockNumber) -> Self {
131
		let state_per_head = heads.into_iter().collect::<HashMap<_, _>>();
132
133
134
135
		let view = View::new(
			state_per_head.keys().cloned(),
			finalized_number,
		);
136
		Self {
137
			view,
138
139
140
141
142
143
144
			span_per_head: state_per_head,
		}
	}

	/// Returns the span per head map.
	///
	/// For each head there exists one span in this map.
145
	pub fn span_per_head(&self) -> &HashMap<Hash, Arc<jaeger::Span>> {
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
		&self.span_per_head
	}
}

impl PartialEq for OurView {
	fn eq(&self, other: &Self) -> bool {
		self.view == other.view
	}
}

impl std::ops::Deref for OurView {
	type Target = View;

	fn deref(&self) -> &View {
		&self.view
	}
}

164
/// Construct a new [`OurView`] with the given chain heads, finalized number 0 and disabled [`jaeger::Span`]'s.
165
166
167
168
169
170
171
172
173
174
175
176
177
178
///
/// NOTE: Use for tests only.
///
/// # Example
///
/// ```
/// # use polkadot_node_network_protocol::our_view;
/// # use polkadot_primitives::v1::Hash;
/// let our_view = our_view![Hash::repeat_byte(1), Hash::repeat_byte(2)];
/// ```
#[macro_export]
macro_rules! our_view {
	( $( $hash:expr ),* $(,)? ) => {
		$crate::OurView::new(
179
			vec![ $( $hash.clone() ),* ].into_iter().map(|h| (h, $crate::Arc::new($crate::jaeger::Span::Disabled))),
180
181
182
183
184
			0,
		)
	};
}

185
186
/// A succinct representation of a peer's view. This consists of a bounded amount of chain heads
/// and the highest known finalized block number.
187
188
189
///
/// Up to `N` (5?) chain heads.
#[derive(Default, Debug, Clone, PartialEq, Eq, Encode, Decode)]
190
191
pub struct View {
	/// A bounded amount of chain heads.
192
193
	/// Invariant: Sorted.
	heads: Vec<Hash>,
194
195
196
197
198
	/// The highest known finalized block number.
	pub finalized_number: BlockNumber,
}

/// Construct a new view with the given chain heads and finalized number 0.
199
///
200
/// NOTE: Use for tests only.
201
///
202
203
/// # Example
///
204
205
206
207
/// ```
/// # use polkadot_node_network_protocol::view;
/// # use polkadot_primitives::v1::Hash;
/// let view = view![Hash::repeat_byte(1), Hash::repeat_byte(2)];
208
209
210
211
/// ```
#[macro_export]
macro_rules! view {
	( $( $hash:expr ),* $(,)? ) => {
212
		$crate::View::new(vec![ $( $hash.clone() ),* ], 0)
213
214
	};
}
215
216

impl View {
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
255
	/// Construct a new view based on heads and a finalized block number.
	pub fn new(heads: impl IntoIterator<Item=Hash>, finalized_number: BlockNumber) -> Self
	{
		let mut heads = heads.into_iter().collect::<Vec<Hash>>();
		heads.sort();
		Self {
			heads,
			finalized_number,
		}
	}

	/// Start with no heads, but only a finalized block number.
	pub fn with_finalized(finalized_number: BlockNumber) -> Self {
		Self {
			heads: Vec::new(),
			finalized_number,
		}
	}

	/// Obtain the number of heads that are in view.
	pub fn len(&self) -> usize {
		self.heads.len()
	}

	/// Check if the number of heads contained, is null.
	pub fn is_empty(&self) -> bool {
		self.heads.is_empty()
	}

	/// Obtain an iterator over all heads.
	pub fn iter<'a>(&'a self) -> impl Iterator<Item=&'a Hash> {
		self.heads.iter()
	}

	/// Obtain an iterator over all heads.
	pub fn into_iter(self) -> impl Iterator<Item=Hash> {
		self.heads.into_iter()
	}

256
257
258
259
260
261
	/// Replace `self` with `new`.
	///
	/// Returns an iterator that will yield all elements of `new` that were not part of `self`.
	pub fn replace_difference(&mut self, new: View) -> impl Iterator<Item = &Hash> {
		let old = std::mem::replace(self, new);

262
		self.heads.iter().filter(move |h| !old.contains(h))
263
264
	}

265
266
	/// Returns an iterator of the hashes present in `Self` but not in `other`.
	pub fn difference<'a>(&'a self, other: &'a View) -> impl Iterator<Item = &'a Hash> + 'a {
267
		self.heads.iter().filter(move |h| !other.contains(h))
268
269
270
271
	}

	/// An iterator containing hashes present in both `Self` and in `other`.
	pub fn intersection<'a>(&'a self, other: &'a View) -> impl Iterator<Item = &'a Hash> + 'a {
272
		self.heads.iter().filter(move |h| other.contains(h))
273
274
275
276
	}

	/// Whether the view contains a given hash.
	pub fn contains(&self, hash: &Hash) -> bool {
277
		self.heads.contains(hash)
278
	}
279
280
281
282
283
284
285
286

	/// Check if two views have the same heads.
	///
	/// Equivalent to the `PartialEq` fn,
	/// but ignores the `finalized_number` field.
	pub fn check_heads_eq(&self, other: &Self) -> bool {
		self.heads == other.heads
	}
287
288
289
290
291
292
}

/// v1 protocol types.
pub mod v1 {
	use polkadot_primitives::v1::{
		Hash, CollatorId, Id as ParaId, ErasureChunk, CandidateReceipt,
293
		SignedAvailabilityBitfield, PoV, CandidateHash, ValidatorIndex, CandidateIndex, AvailableData,
294
295
296
297
	};
	use polkadot_node_primitives::{
		SignedFullStatement,
		approval::{IndirectAssignmentCert, IndirectSignedApprovalVote},
298
299
300
	};
	use parity_scale_codec::{Encode, Decode};
	use super::RequestId;
301
	use std::convert::TryFrom;
302
303

	/// Network messages used by the availability distribution subsystem
304
	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
305
306
	pub enum AvailabilityDistributionMessage {
		/// An erasure chunk for a given candidate hash.
307
		#[codec(index = 0)]
308
		Chunk(CandidateHash, ErasureChunk),
309
310
	}

311
	/// Network messages used by the availability recovery subsystem.
312
	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
313
314
315
316
317
318
	pub enum AvailabilityRecoveryMessage {
		/// Request a chunk for a given candidate hash and validator index.
		RequestChunk(RequestId, CandidateHash, ValidatorIndex),
		/// Respond with chunk for a given candidate hash and validator index.
		/// The response may be `None` if the requestee does not have the chunk.
		Chunk(RequestId, Option<ErasureChunk>),
319
320
321
322
323
		/// Request full data for a given candidate hash.
		RequestFullData(RequestId, CandidateHash),
		/// Respond with full data for a given candidate hash.
		/// The response may be `None` if the requestee does not have the data.
		FullData(RequestId, Option<AvailableData>),
324
325
	}

326
	/// Network messages used by the bitfield distribution subsystem.
327
	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
328
329
	pub enum BitfieldDistributionMessage {
		/// A signed availability bitfield for a given relay-parent hash.
330
		#[codec(index = 0)]
331
332
333
334
		Bitfield(Hash, SignedAvailabilityBitfield),
	}

	/// Network messages used by the PoV distribution subsystem.
335
	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
336
337
338
	pub enum PoVDistributionMessage {
		/// Notification that we are awaiting the given PoVs (by hash) against a
		/// specific relay-parent hash.
339
		#[codec(index = 0)]
340
341
		Awaiting(Hash, Vec<Hash>),
		/// Notification of an awaited PoV, in a given relay-parent context.
342
		/// (relay_parent, pov_hash, compressed_pov)
343
		#[codec(index = 1)]
344
		SendPoV(Hash, Hash, CompressedPoV),
345
346
347
	}

	/// Network messages used by the statement distribution subsystem.
348
	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
349
350
	pub enum StatementDistributionMessage {
		/// A signed full statement under a given relay-parent.
351
		#[codec(index = 0)]
352
353
354
		Statement(Hash, SignedFullStatement)
	}

355
356
357
358
359
360
	/// Network messages used by the approval distribution subsystem.
	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
	pub enum ApprovalDistributionMessage {
		/// Assignments for candidates in recent, unfinalized blocks.
		///
		/// Actually checking the assignment may yield a different result.
361
		#[codec(index = 0)]
362
363
		Assignments(Vec<(IndirectAssignmentCert, CandidateIndex)>),
		/// Approvals for candidates in some recent, unfinalized block.
364
		#[codec(index = 1)]
365
366
367
368
		Approvals(Vec<IndirectSignedApprovalVote>),
	}

	#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
369
370
371
372
373
374
375
376
377
378
379
380
381
	#[allow(missing_docs)]
	pub enum CompressedPoVError {
		#[error("Failed to compress a PoV")]
		Compress,
		#[error("Failed to decompress a PoV")]
		Decompress,
		#[error("Failed to decode the uncompressed PoV")]
		Decode,
		#[error("Architecture is not supported")]
		NotSupported,
	}

	/// SCALE and Zstd encoded [`PoV`].
382
	#[derive(Clone, Encode, Decode, PartialEq, Eq)]
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
	pub struct CompressedPoV(Vec<u8>);

	impl CompressedPoV {
		/// Compress the given [`PoV`] and returns a [`CompressedPoV`].
		#[cfg(not(target_os = "unknown"))]
		pub fn compress(pov: &PoV) -> Result<Self, CompressedPoVError> {
			zstd::encode_all(pov.encode().as_slice(), 3).map_err(|_| CompressedPoVError::Compress).map(Self)
		}

		/// Compress the given [`PoV`] and returns a [`CompressedPoV`].
		#[cfg(target_os = "unknown")]
		pub fn compress(_: &PoV) -> Result<Self, CompressedPoVError> {
			Err(CompressedPoVError::NotSupported)
		}

		/// Decompress `self` and returns the [`PoV`] on success.
		#[cfg(not(target_os = "unknown"))]
		pub fn decompress(&self) -> Result<PoV, CompressedPoVError> {
			use std::io::Read;
			const MAX_POV_BLOCK_SIZE: usize = 32 * 1024 * 1024;

			struct InputDecoder<'a, T: std::io::BufRead>(&'a mut zstd::Decoder<T>, usize);
			impl<'a, T: std::io::BufRead> parity_scale_codec::Input for InputDecoder<'a, T> {
				fn read(&mut self, into: &mut [u8]) -> Result<(), parity_scale_codec::Error> {
					self.1 = self.1.saturating_add(into.len());
					if self.1 > MAX_POV_BLOCK_SIZE {
						return Err("pov block too big".into())
					}
					self.0.read_exact(into).map_err(Into::into)
				}
				fn remaining_len(&mut self) -> Result<Option<usize>, parity_scale_codec::Error> {
					Ok(None)
				}
			}

			let mut decoder = zstd::Decoder::new(self.0.as_slice()).map_err(|_| CompressedPoVError::Decompress)?;
			PoV::decode(&mut InputDecoder(&mut decoder, 0)).map_err(|_| CompressedPoVError::Decode)
		}

		/// Decompress `self` and returns the [`PoV`] on success.
		#[cfg(target_os = "unknown")]
		pub fn decompress(&self) -> Result<PoV, CompressedPoVError> {
			Err(CompressedPoVError::NotSupported)
		}
	}

429
	impl std::fmt::Debug for CompressedPoV {
430
		fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
431
432
433
434
			write!(f, "CompressedPoV({} bytes)", self.0.len())
		}
	}

435
	/// Network messages used by the collator protocol subsystem
436
	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
437
438
	pub enum CollatorProtocolMessage {
		/// Declare the intent to advertise collations under a collator ID.
439
		#[codec(index = 0)]
440
441
442
		Declare(CollatorId),
		/// Advertise a collation to a validator. Can only be sent once the peer has declared
		/// that they are a collator with given ID.
443
		#[codec(index = 1)]
444
445
		AdvertiseCollation(Hash, ParaId),
		/// Request the advertised collation at that relay-parent.
446
		#[codec(index = 2)]
447
448
		RequestCollation(RequestId, Hash, ParaId),
		/// A requested collation.
449
		#[codec(index = 3)]
450
		Collation(RequestId, CandidateReceipt, CompressedPoV),
451
452
453
		/// A collation sent to a validator was seconded.
		#[codec(index = 4)]
		CollationSeconded(SignedFullStatement),
454
455
456
	}

	/// All network messages on the validation peer-set.
457
	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
458
459
	pub enum ValidationProtocol {
		/// Availability distribution messages
460
		#[codec(index = 0)]
461
462
		AvailabilityDistribution(AvailabilityDistributionMessage),
		/// Bitfield distribution messages
463
		#[codec(index = 1)]
464
465
		BitfieldDistribution(BitfieldDistributionMessage),
		/// PoV Distribution messages
466
		#[codec(index = 2)]
467
468
		PoVDistribution(PoVDistributionMessage),
		/// Statement distribution messages
469
		#[codec(index = 3)]
470
		StatementDistribution(StatementDistributionMessage),
471
		/// Availability recovery messages
472
		#[codec(index = 4)]
473
		AvailabilityRecovery(AvailabilityRecoveryMessage),
474
		/// Approval distribution messages
475
		#[codec(index = 5)]
476
		ApprovalDistribution(ApprovalDistributionMessage),
477
478
479
480
481
482
	}

	impl_try_from!(ValidationProtocol, AvailabilityDistribution, AvailabilityDistributionMessage);
	impl_try_from!(ValidationProtocol, BitfieldDistribution, BitfieldDistributionMessage);
	impl_try_from!(ValidationProtocol, PoVDistribution, PoVDistributionMessage);
	impl_try_from!(ValidationProtocol, StatementDistribution, StatementDistributionMessage);
483
	impl_try_from!(ValidationProtocol, ApprovalDistribution, ApprovalDistributionMessage);
484
485

	/// All network messages on the collation peer-set.
486
	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
487
488
	pub enum CollationProtocol {
		/// Collator protocol messages
489
		#[codec(index = 0)]
490
491
492
493
494
		CollatorProtocol(CollatorProtocolMessage),
	}

	impl_try_from!(CollationProtocol, CollatorProtocol, CollatorProtocolMessage);
}
495
496
497
498
499
500
501
502
503
504
505
506
507
508

#[cfg(test)]
mod tests {
	use polkadot_primitives::v1::PoV;
	use super::v1::{CompressedPoV, CompressedPoVError};

	#[test]
	fn decompress_huge_pov_block_fails() {
		let pov = PoV { block_data: vec![0; 63 * 1024 * 1024].into() };

		let compressed = CompressedPoV::compress(&pov).unwrap();
		assert_eq!(CompressedPoVError::Decode, compressed.decompress().unwrap_err());
	}
}