referrerpolicy=no-referrer-when-downgrade

polkadot_node_network_protocol/
lib.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
3
4// Polkadot is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Polkadot is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16
17//! Network protocol types for parachains.
18
19#![deny(unused_crate_dependencies)]
20#![warn(missing_docs)]
21
22use codec::{Decode, Encode};
23use polkadot_primitives::{BlockNumber, Hash};
24use std::fmt;
25
26#[doc(hidden)]
27pub use sc_network::IfDisconnected;
28pub use sc_network_types::PeerId;
29#[doc(hidden)]
30pub use std::sync::Arc;
31
32mod reputation;
33pub use self::reputation::{ReputationChange, UnifiedReputationChange};
34
35/// Peer-sets and protocols used for parachains.
36pub mod peer_set;
37
38/// Request/response protocols used in Polkadot.
39pub mod request_response;
40
41/// Accessing authority discovery service
42pub mod authority_discovery;
43/// Grid topology support module
44pub mod grid_topology;
45
46/// The minimum amount of peers to send gossip messages to.
47pub const MIN_GOSSIP_PEERS: usize = 25;
48
49/// An error indicating that this the over-arching message type had the wrong variant
50#[derive(Debug, Clone, Copy, PartialEq)]
51pub struct WrongVariant;
52
53impl fmt::Display for WrongVariant {
54	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
55		write!(formatter, "Wrong message variant")
56	}
57}
58
59impl std::error::Error for WrongVariant {}
60
61/// The advertised role of a node.
62#[derive(Debug, Clone, Copy, PartialEq)]
63pub enum ObservedRole {
64	/// A light node.
65	Light,
66	/// A full node.
67	Full,
68	/// A node claiming to be an authority (unauthenticated)
69	Authority,
70}
71
72impl From<sc_network::ObservedRole> for ObservedRole {
73	fn from(role: sc_network::ObservedRole) -> ObservedRole {
74		match role {
75			sc_network::ObservedRole::Light => ObservedRole::Light,
76			sc_network::ObservedRole::Authority => ObservedRole::Authority,
77			sc_network::ObservedRole::Full => ObservedRole::Full,
78		}
79	}
80}
81
82impl Into<sc_network::ObservedRole> for ObservedRole {
83	fn into(self) -> sc_network::ObservedRole {
84		match self {
85			ObservedRole::Light => sc_network::ObservedRole::Light,
86			ObservedRole::Full => sc_network::ObservedRole::Full,
87			ObservedRole::Authority => sc_network::ObservedRole::Authority,
88		}
89	}
90}
91
92/// Specialized wrapper around [`View`].
93#[derive(Debug, Clone, Default)]
94pub struct OurView {
95	view: View,
96}
97
98impl OurView {
99	/// Creates a new instance.
100	pub fn new(heads: impl IntoIterator<Item = Hash>, finalized_number: BlockNumber) -> Self {
101		let view = View::new(heads, finalized_number);
102		Self { view }
103	}
104}
105
106impl PartialEq for OurView {
107	fn eq(&self, other: &Self) -> bool {
108		self.view == other.view
109	}
110}
111
112impl std::ops::Deref for OurView {
113	type Target = View;
114
115	fn deref(&self) -> &View {
116		&self.view
117	}
118}
119
120/// Construct a new [`OurView`] with the given chain heads, finalized number 0
121///
122/// NOTE: Use for tests only.
123///
124/// # Example
125///
126/// ```
127/// # use polkadot_node_network_protocol::our_view;
128/// # use polkadot_primitives::Hash;
129/// let our_view = our_view![Hash::repeat_byte(1), Hash::repeat_byte(2)];
130/// ```
131#[macro_export]
132macro_rules! our_view {
133	( $( $hash:expr ),* $(,)? ) => {
134		$crate::OurView::new(
135			vec![ $( $hash.clone() ),* ].into_iter().map(|h| h),
136			0,
137		)
138	};
139}
140
141/// A succinct representation of a peer's view. This consists of a bounded amount of chain heads
142/// and the highest known finalized block number.
143///
144/// Up to `N` (5?) chain heads.
145#[derive(Default, Debug, Clone, PartialEq, Eq, Encode, Decode)]
146pub struct View {
147	/// A bounded amount of chain heads.
148	/// Invariant: Sorted.
149	heads: Vec<Hash>,
150	/// The highest known finalized block number.
151	pub finalized_number: BlockNumber,
152}
153
154/// Construct a new view with the given chain heads and finalized number 0.
155///
156/// NOTE: Use for tests only.
157///
158/// # Example
159///
160/// ```
161/// # use polkadot_node_network_protocol::view;
162/// # use polkadot_primitives::Hash;
163/// let view = view![Hash::repeat_byte(1), Hash::repeat_byte(2)];
164/// ```
165#[macro_export]
166macro_rules! view {
167	( $( $hash:expr ),* $(,)? ) => {
168		$crate::View::new(vec![ $( $hash.clone() ),* ], 0)
169	};
170}
171
172impl View {
173	/// Construct a new view based on heads and a finalized block number.
174	pub fn new(heads: impl IntoIterator<Item = Hash>, finalized_number: BlockNumber) -> Self {
175		let mut heads = heads.into_iter().collect::<Vec<Hash>>();
176		heads.sort();
177		Self { heads, finalized_number }
178	}
179
180	/// Start with no heads, but only a finalized block number.
181	pub fn with_finalized(finalized_number: BlockNumber) -> Self {
182		Self { heads: Vec::new(), finalized_number }
183	}
184
185	/// Obtain the number of heads that are in view.
186	pub fn len(&self) -> usize {
187		self.heads.len()
188	}
189
190	/// Check if the number of heads contained, is null.
191	pub fn is_empty(&self) -> bool {
192		self.heads.is_empty()
193	}
194
195	/// Obtain an iterator over all heads.
196	pub fn iter(&self) -> impl Iterator<Item = &Hash> {
197		self.heads.iter()
198	}
199
200	/// Obtain an iterator over all heads.
201	pub fn into_iter(self) -> impl Iterator<Item = Hash> {
202		self.heads.into_iter()
203	}
204
205	/// Replace `self` with `new`.
206	///
207	/// Returns an iterator that will yield all elements of `new` that were not part of `self`.
208	pub fn replace_difference(&mut self, new: View) -> impl Iterator<Item = &Hash> {
209		let old = std::mem::replace(self, new);
210
211		self.heads.iter().filter(move |h| !old.contains(h))
212	}
213
214	/// Returns an iterator of the hashes present in `Self` but not in `other`.
215	pub fn difference<'a>(&'a self, other: &'a View) -> impl Iterator<Item = &'a Hash> + 'a {
216		self.heads.iter().filter(move |h| !other.contains(h))
217	}
218
219	/// An iterator containing hashes present in both `Self` and in `other`.
220	pub fn intersection<'a>(&'a self, other: &'a View) -> impl Iterator<Item = &'a Hash> + 'a {
221		self.heads.iter().filter(move |h| other.contains(h))
222	}
223
224	/// Whether the view contains a given hash.
225	pub fn contains(&self, hash: &Hash) -> bool {
226		self.heads.contains(hash)
227	}
228
229	/// Check if two views have the same heads.
230	///
231	/// Equivalent to the `PartialEq` function,
232	/// but ignores the `finalized_number` field.
233	pub fn check_heads_eq(&self, other: &Self) -> bool {
234		self.heads == other.heads
235	}
236}
237
238/// A protocol-versioned type for validation.
239#[derive(Debug, Clone, PartialEq, Eq)]
240pub enum ValidationProtocols<V3> {
241	/// V3 type.
242	V3(V3),
243}
244
245/// A protocol-versioned type for collation.
246#[derive(Debug, Clone, PartialEq, Eq)]
247pub enum CollationProtocols<V1, V2> {
248	/// V1 type.
249	V1(V1),
250	/// V2 type.
251	V2(V2),
252}
253
254impl<V3: Clone> ValidationProtocols<&'_ V3> {
255	/// Convert to a fully-owned version of the message.
256	pub fn clone_inner(&self) -> ValidationProtocols<V3> {
257		match *self {
258			ValidationProtocols::V3(inner) => ValidationProtocols::V3(inner.clone()),
259		}
260	}
261}
262
263impl<V1: Clone, V2: Clone> CollationProtocols<&'_ V1, &'_ V2> {
264	/// Convert to a fully-owned version of the message.
265	pub fn clone_inner(&self) -> CollationProtocols<V1, V2> {
266		match *self {
267			CollationProtocols::V1(inner) => CollationProtocols::V1(inner.clone()),
268			CollationProtocols::V2(inner) => CollationProtocols::V2(inner.clone()),
269		}
270	}
271}
272
273/// All supported versions of the validation protocol message.
274pub type VersionedValidationProtocol = ValidationProtocols<v3::ValidationProtocol>;
275
276impl From<v3::ValidationProtocol> for VersionedValidationProtocol {
277	fn from(v3: v3::ValidationProtocol) -> Self {
278		VersionedValidationProtocol::V3(v3)
279	}
280}
281
282/// All supported versions of the collation protocol message.
283pub type VersionedCollationProtocol =
284	CollationProtocols<v1::CollationProtocol, v2::CollationProtocol>;
285
286impl From<v1::CollationProtocol> for VersionedCollationProtocol {
287	fn from(v1: v1::CollationProtocol) -> Self {
288		VersionedCollationProtocol::V1(v1)
289	}
290}
291
292impl From<v2::CollationProtocol> for VersionedCollationProtocol {
293	fn from(v2: v2::CollationProtocol) -> Self {
294		VersionedCollationProtocol::V2(v2)
295	}
296}
297
298macro_rules! impl_versioned_validation_full_protocol_from {
299	($from:ty, $out:ty, $variant:ident) => {
300		impl From<$from> for $out {
301			fn from(versioned_from: $from) -> $out {
302				match versioned_from {
303					ValidationProtocols::V3(x) => ValidationProtocols::V3(x.into()),
304				}
305			}
306		}
307	};
308}
309
310macro_rules! impl_versioned_collation_full_protocol_from {
311	($from:ty, $out:ty, $variant:ident) => {
312		impl From<$from> for $out {
313			fn from(versioned_from: $from) -> $out {
314				match versioned_from {
315					CollationProtocols::V1(x) => CollationProtocols::V1(x.into()),
316					CollationProtocols::V2(x) => CollationProtocols::V2(x.into()),
317				}
318			}
319		}
320	};
321}
322
323/// Implement `TryFrom` for one versioned validation enum variant into the inner type.
324/// `$m_ty::$variant(inner) -> Ok(inner)`
325macro_rules! impl_versioned_validation_try_from {
326	(
327		$from:ty,
328		$out:ty,
329		$v3_pat:pat => $v3_out:expr
330	) => {
331		impl TryFrom<$from> for $out {
332			type Error = crate::WrongVariant;
333
334			fn try_from(x: $from) -> Result<$out, Self::Error> {
335				#[allow(unreachable_patterns)] // when there is only one variant
336				match x {
337					ValidationProtocols::V3($v3_pat) => Ok(ValidationProtocols::V3($v3_out)),
338					_ => Err(crate::WrongVariant),
339				}
340			}
341		}
342
343		impl<'a> TryFrom<&'a $from> for $out {
344			type Error = crate::WrongVariant;
345
346			fn try_from(x: &'a $from) -> Result<$out, Self::Error> {
347				#[allow(unreachable_patterns)] // when there is only one variant
348				match x {
349					ValidationProtocols::V3($v3_pat) =>
350						Ok(ValidationProtocols::V3($v3_out.clone())),
351					_ => Err(crate::WrongVariant),
352				}
353			}
354		}
355	};
356}
357
358/// Implement `TryFrom` for one versioned collation enum variant into the inner type.
359/// `$m_ty::$variant(inner) -> Ok(inner)`
360macro_rules! impl_versioned_collation_try_from {
361	(
362		$from:ty,
363		$out:ty,
364		$v1_pat:pat => $v1_out:expr,
365		$v2_pat:pat => $v2_out:expr
366	) => {
367		impl TryFrom<$from> for $out {
368			type Error = crate::WrongVariant;
369
370			fn try_from(x: $from) -> Result<$out, Self::Error> {
371				#[allow(unreachable_patterns)] // when there is only one variant
372				match x {
373					CollationProtocols::V1($v1_pat) => Ok(CollationProtocols::V1($v1_out)),
374					CollationProtocols::V2($v2_pat) => Ok(CollationProtocols::V2($v2_out)),
375					_ => Err(crate::WrongVariant),
376				}
377			}
378		}
379
380		impl<'a> TryFrom<&'a $from> for $out {
381			type Error = crate::WrongVariant;
382
383			fn try_from(x: &'a $from) -> Result<$out, Self::Error> {
384				#[allow(unreachable_patterns)] // when there is only one variant
385				match x {
386					CollationProtocols::V1($v1_pat) => Ok(CollationProtocols::V1($v1_out.clone())),
387					CollationProtocols::V2($v2_pat) => Ok(CollationProtocols::V2($v2_out.clone())),
388					_ => Err(crate::WrongVariant),
389				}
390			}
391		}
392	};
393}
394
395/// Version-annotated messages used by the bitfield distribution subsystem.
396pub type BitfieldDistributionMessage = ValidationProtocols<v3::BitfieldDistributionMessage>;
397impl_versioned_validation_full_protocol_from!(
398	BitfieldDistributionMessage,
399	VersionedValidationProtocol,
400	BitfieldDistribution
401);
402impl_versioned_validation_try_from!(
403	VersionedValidationProtocol,
404	BitfieldDistributionMessage,
405	v3::ValidationProtocol::BitfieldDistribution(x) => x
406);
407
408/// Version-annotated messages used by the statement distribution subsystem.
409pub type StatementDistributionMessage = ValidationProtocols<v3::StatementDistributionMessage>;
410impl_versioned_validation_full_protocol_from!(
411	StatementDistributionMessage,
412	VersionedValidationProtocol,
413	StatementDistribution
414);
415impl_versioned_validation_try_from!(
416	VersionedValidationProtocol,
417	StatementDistributionMessage,
418	v3::ValidationProtocol::StatementDistribution(x) => x
419);
420
421/// Version-annotated messages used by the approval distribution subsystem.
422pub type ApprovalDistributionMessage = ValidationProtocols<v3::ApprovalDistributionMessage>;
423impl_versioned_validation_full_protocol_from!(
424	ApprovalDistributionMessage,
425	VersionedValidationProtocol,
426	ApprovalDistribution
427);
428impl_versioned_validation_try_from!(
429	VersionedValidationProtocol,
430	ApprovalDistributionMessage,
431	v3::ValidationProtocol::ApprovalDistribution(x) => x
432
433);
434
435/// Version-annotated messages used by the gossip-support subsystem (this is void).
436pub type GossipSupportNetworkMessage = ValidationProtocols<v3::GossipSupportNetworkMessage>;
437
438// This is a void enum placeholder, so never gets sent over the wire.
439impl TryFrom<VersionedValidationProtocol> for GossipSupportNetworkMessage {
440	type Error = WrongVariant;
441	fn try_from(_: VersionedValidationProtocol) -> Result<Self, Self::Error> {
442		Err(WrongVariant)
443	}
444}
445
446impl<'a> TryFrom<&'a VersionedValidationProtocol> for GossipSupportNetworkMessage {
447	type Error = WrongVariant;
448	fn try_from(_: &'a VersionedValidationProtocol) -> Result<Self, Self::Error> {
449		Err(WrongVariant)
450	}
451}
452
453/// Version-annotated messages used by the collator protocol subsystem.
454pub type CollatorProtocolMessage =
455	CollationProtocols<v1::CollatorProtocolMessage, v2::CollatorProtocolMessage>;
456impl_versioned_collation_full_protocol_from!(
457	CollatorProtocolMessage,
458	VersionedCollationProtocol,
459	CollatorProtocol
460);
461impl_versioned_collation_try_from!(
462	VersionedCollationProtocol,
463	CollatorProtocolMessage,
464	v1::CollationProtocol::CollatorProtocol(x) => x,
465	v2::CollationProtocol::CollatorProtocol(x) => x
466);
467
468/// v1 notification protocol types.
469pub mod v1 {
470	use codec::{Decode, Encode};
471
472	use polkadot_primitives::{CollatorId, CollatorSignature, Hash, Id as ParaId};
473
474	use polkadot_node_primitives::UncheckedSignedFullStatement;
475
476	/// Network messages used by the collator protocol subsystem
477	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
478	pub enum CollatorProtocolMessage {
479		/// Declare the intent to advertise collations under a collator ID, attaching a
480		/// signature of the `PeerId` of the node using the given collator ID key.
481		#[codec(index = 0)]
482		Declare(CollatorId, ParaId, CollatorSignature),
483		/// Advertise a collation to a validator. Can only be sent once the peer has
484		/// declared that they are a collator with given ID.
485		#[codec(index = 1)]
486		AdvertiseCollation(Hash),
487		/// A collation sent to a validator was seconded.
488		#[codec(index = 4)]
489		CollationSeconded(Hash, UncheckedSignedFullStatement),
490	}
491
492	/// All network messages on the collation peer-set.
493	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq, derive_more::From)]
494	pub enum CollationProtocol {
495		/// Collator protocol messages
496		#[codec(index = 0)]
497		#[from]
498		CollatorProtocol(CollatorProtocolMessage),
499	}
500
501	/// Get the payload that should be signed and included in a `Declare` message.
502	///
503	/// The payload is the local peer id of the node, which serves to prove that it
504	/// controls the collator key it is declaring an intention to collate under.
505	pub fn declare_signature_payload(peer_id: &sc_network_types::PeerId) -> Vec<u8> {
506		let mut payload = peer_id.to_bytes();
507		payload.extend_from_slice(b"COLL");
508		payload
509	}
510}
511
512/// v2 network protocol types.
513pub mod v2 {
514	use codec::{Decode, Encode};
515
516	use polkadot_primitives::{CandidateHash, CollatorId, CollatorSignature, Hash, Id as ParaId};
517
518	use polkadot_node_primitives::UncheckedSignedFullStatement;
519
520	/// This parts of the protocol did not change from v1, so just alias them in v2.
521	pub use super::v1::declare_signature_payload;
522
523	/// Network messages used by the collator protocol subsystem
524	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
525	pub enum CollatorProtocolMessage {
526		/// Declare the intent to advertise collations under a collator ID, attaching a
527		/// signature of the `PeerId` of the node using the given collator ID key.
528		#[codec(index = 0)]
529		Declare(CollatorId, ParaId, CollatorSignature),
530		/// Advertise a collation to a validator. Can only be sent once the peer has
531		/// declared that they are a collator with given ID.
532		#[codec(index = 1)]
533		AdvertiseCollation {
534			/// Hash of the relay parent advertised collation is based on.
535			relay_parent: Hash,
536			/// Candidate hash.
537			candidate_hash: CandidateHash,
538			/// Parachain head data hash before candidate execution.
539			parent_head_data_hash: Hash,
540		},
541		/// A collation sent to a validator was seconded.
542		#[codec(index = 4)]
543		CollationSeconded(Hash, UncheckedSignedFullStatement),
544	}
545
546	/// All network messages on the collation peer-set.
547	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq, derive_more::From)]
548	pub enum CollationProtocol {
549		/// Collator protocol messages
550		#[codec(index = 0)]
551		#[from]
552		CollatorProtocol(CollatorProtocolMessage),
553	}
554}
555
556/// v3 network protocol types.
557/// Purpose is for changing ApprovalDistributionMessage to
558/// include more than one assignment and approval in a message.
559pub mod v3 {
560	use bitvec::{order::Lsb0, slice::BitSlice, vec::BitVec};
561	use codec::{Decode, Encode};
562
563	use polkadot_primitives::{
564		CandidateHash, GroupIndex, Hash, Id as ParaId, UncheckedSignedAvailabilityBitfield,
565		UncheckedSignedStatement,
566	};
567
568	use polkadot_node_primitives::approval::v2::{
569		CandidateBitfield, IndirectAssignmentCertV2, IndirectSignedApprovalVoteV2,
570	};
571
572	/// This parts of the protocol did not change from v2, so just alias them in v3.
573	pub use super::v2::declare_signature_payload;
574
575	/// Network messages used by the bitfield distribution subsystem.
576	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
577	pub enum BitfieldDistributionMessage {
578		/// A signed availability bitfield for a given relay-parent hash.
579		#[codec(index = 0)]
580		Bitfield(Hash, UncheckedSignedAvailabilityBitfield),
581	}
582
583	/// Bitfields indicating the statements that are known or undesired
584	/// about a candidate.
585	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
586	pub struct StatementFilter {
587		/// Seconded statements. '1' is known or undesired.
588		pub seconded_in_group: BitVec<u8, Lsb0>,
589		/// Valid statements. '1' is known or undesired.
590		pub validated_in_group: BitVec<u8, Lsb0>,
591	}
592
593	impl StatementFilter {
594		/// Create a new blank filter with the given group size.
595		pub fn blank(group_size: usize) -> Self {
596			StatementFilter {
597				seconded_in_group: BitVec::repeat(false, group_size),
598				validated_in_group: BitVec::repeat(false, group_size),
599			}
600		}
601
602		/// Create a new full filter with the given group size.
603		pub fn full(group_size: usize) -> Self {
604			StatementFilter {
605				seconded_in_group: BitVec::repeat(true, group_size),
606				validated_in_group: BitVec::repeat(true, group_size),
607			}
608		}
609
610		/// Whether the filter has a specific expected length, consistent across both
611		/// bitfields.
612		pub fn has_len(&self, len: usize) -> bool {
613			self.seconded_in_group.len() == len && self.validated_in_group.len() == len
614		}
615
616		/// Determine the number of backing validators in the statement filter.
617		pub fn backing_validators(&self) -> usize {
618			self.seconded_in_group
619				.iter()
620				.by_vals()
621				.zip(self.validated_in_group.iter().by_vals())
622				.filter(|&(s, v)| s || v) // no double-counting
623				.count()
624		}
625
626		/// Whether the statement filter has at least one seconded statement.
627		pub fn has_seconded(&self) -> bool {
628			self.seconded_in_group.iter().by_vals().any(|x| x)
629		}
630
631		/// Mask out `Seconded` statements in `self` according to the provided
632		/// bitvec. Bits appearing in `mask` will not appear in `self` afterwards.
633		pub fn mask_seconded(&mut self, mask: &BitSlice<u8, Lsb0>) {
634			for (mut x, mask) in self
635				.seconded_in_group
636				.iter_mut()
637				.zip(mask.iter().by_vals().chain(std::iter::repeat(false)))
638			{
639				// (x, mask) => x
640				// (true, true) => false
641				// (true, false) => true
642				// (false, true) => false
643				// (false, false) => false
644				*x = *x && !mask;
645			}
646		}
647
648		/// Mask out `Valid` statements in `self` according to the provided
649		/// bitvec. Bits appearing in `mask` will not appear in `self` afterwards.
650		pub fn mask_valid(&mut self, mask: &BitSlice<u8, Lsb0>) {
651			for (mut x, mask) in self
652				.validated_in_group
653				.iter_mut()
654				.zip(mask.iter().by_vals().chain(std::iter::repeat(false)))
655			{
656				// (x, mask) => x
657				// (true, true) => false
658				// (true, false) => true
659				// (false, true) => false
660				// (false, false) => false
661				*x = *x && !mask;
662			}
663		}
664	}
665
666	/// A manifest of a known backed candidate, along with a description
667	/// of the statements backing it.
668	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
669	pub struct BackedCandidateManifest {
670		/// The relay-parent of the candidate.
671		pub relay_parent: Hash,
672		/// The hash of the candidate.
673		pub candidate_hash: CandidateHash,
674		/// The group index backing the candidate at the relay-parent.
675		pub group_index: GroupIndex,
676		/// The para ID of the candidate. It is illegal for this to
677		/// be a para ID which is not assigned to the group indicated
678		/// in this manifest.
679		pub para_id: ParaId,
680		/// The head-data corresponding to the candidate.
681		pub parent_head_data_hash: Hash,
682		/// A statement filter which indicates which validators in the
683		/// para's group at the relay-parent have validated this candidate
684		/// and issued statements about it, to the advertiser's knowledge.
685		///
686		/// This MUST have exactly the minimum amount of bytes
687		/// necessary to represent the number of validators in the assigned
688		/// backing group as-of the relay-parent.
689		pub statement_knowledge: StatementFilter,
690	}
691
692	/// An acknowledgement of a backed candidate being known.
693	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
694	pub struct BackedCandidateAcknowledgement {
695		/// The hash of the candidate.
696		pub candidate_hash: CandidateHash,
697		/// A statement filter which indicates which validators in the
698		/// para's group at the relay-parent have validated this candidate
699		/// and issued statements about it, to the advertiser's knowledge.
700		///
701		/// This MUST have exactly the minimum amount of bytes
702		/// necessary to represent the number of validators in the assigned
703		/// backing group as-of the relay-parent.
704		pub statement_knowledge: StatementFilter,
705	}
706
707	/// Network messages used by the statement distribution subsystem.
708	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
709	pub enum StatementDistributionMessage {
710		/// A notification of a signed statement in compact form, for a given relay parent.
711		#[codec(index = 0)]
712		Statement(Hash, UncheckedSignedStatement),
713
714		/// A notification of a backed candidate being known by the
715		/// sending node, for the purpose of being requested by the receiving node
716		/// if needed.
717		#[codec(index = 1)]
718		BackedCandidateManifest(BackedCandidateManifest),
719
720		/// A notification of a backed candidate being known by the sending node,
721		/// for the purpose of informing a receiving node which already has the candidate.
722		#[codec(index = 2)]
723		BackedCandidateKnown(BackedCandidateAcknowledgement),
724	}
725
726	/// Network messages used by the approval distribution subsystem.
727	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
728	pub enum ApprovalDistributionMessage {
729		/// Assignments for candidates in recent, unfinalized blocks.
730		/// We use a bitfield to reference claimed candidates, where the bit index is equal to
731		/// candidate index.
732		///
733		/// Actually checking the assignment may yield a different result.
734		///
735		/// TODO at next protocol upgrade opportunity:
736		/// - remove redundancy `candidate_index` vs `core_index`
737		/// - `<https://github.com/paritytech/polkadot-sdk/issues/675>`
738		#[codec(index = 0)]
739		Assignments(Vec<(IndirectAssignmentCertV2, CandidateBitfield)>),
740		/// Approvals for candidates in some recent, unfinalized block.
741		#[codec(index = 1)]
742		Approvals(Vec<IndirectSignedApprovalVoteV2>),
743	}
744
745	/// Dummy network message type, so we will receive connect/disconnect events.
746	#[derive(Debug, Clone, PartialEq, Eq)]
747	pub enum GossipSupportNetworkMessage {}
748
749	/// All network messages on the validation peer-set.
750	#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq, derive_more::From)]
751	pub enum ValidationProtocol {
752		/// Bitfield distribution messages
753		#[codec(index = 1)]
754		#[from]
755		BitfieldDistribution(BitfieldDistributionMessage),
756		/// Statement distribution messages
757		#[codec(index = 3)]
758		#[from]
759		StatementDistribution(StatementDistributionMessage),
760		/// Approval distribution messages
761		#[codec(index = 4)]
762		#[from]
763		ApprovalDistribution(ApprovalDistributionMessage),
764	}
765}
766
767/// Returns the subset of `peers` with the specified `version`.
768pub fn filter_by_peer_version(
769	peers: &[(PeerId, peer_set::ProtocolVersion)],
770	version: peer_set::ProtocolVersion,
771) -> Vec<PeerId> {
772	peers.iter().filter(|(_, v)| v == &version).map(|(p, _)| *p).collect::<Vec<_>>()
773}