messages.rs 34.3 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
23
24
// Copyright 2017-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/>.

//! Message types for the overseer and subsystems.
//!
//! These messages are intended to define the protocol by which different subsystems communicate with each
//! other and signals that they receive from an overseer to coordinate their work.
//! This is intended for use with the `polkadot-overseer` crate.
//!
//! Subsystems' APIs are defined separately from their implementation, leading to easier mocking.

25
use futures::channel::oneshot;
26
use sc_network::Multiaddr;
27
use thiserror::Error;
28
29
30

pub use sc_network::IfDisconnected;

Shawn Tabrizi's avatar
Shawn Tabrizi committed
31
use polkadot_node_network_protocol::{
32
33
	peer_set::PeerSet, request_response::Requests, v1 as protocol_v1, PeerId,
	UnifiedReputationChange,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
34
35
36
37
};
use polkadot_node_primitives::{
	approval::{BlockApprovalMeta, IndirectAssignmentCert, IndirectSignedApprovalVote},
	AvailableData, BabeEpoch, BlockWeight, CandidateVotes, CollationGenerationConfig,
38
39
	CollationSecondedSignal, DisputeMessage, ErasureChunk, PoV, SignedDisputeStatement,
	SignedFullStatement, ValidationResult,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
40
};
41
use polkadot_primitives::v1::{
42
43
44
45
46
47
48
	AuthorityDiscoveryId, BackedCandidate, BlockNumber, CandidateDescriptor, CandidateEvent,
	CandidateHash, CandidateIndex, CandidateReceipt, CollatorId, CommittedCandidateReceipt,
	CoreState, GroupIndex, GroupRotationInfo, Hash, Header as BlockHeader, Id as ParaId,
	InboundDownwardMessage, InboundHrmpMessage, MultiDisputeStatementSet, OccupiedCoreAssumption,
	PersistedValidationData, SessionIndex, SessionInfo, SignedAvailabilityBitfield,
	SignedAvailabilityBitfields, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
	ValidatorSignature,
49
};
50
use polkadot_statement_table::v1::Misbehavior;
51
52
53
use std::{
	collections::{BTreeMap, HashSet},
	sync::Arc,
54
	time::Duration,
55
};
56
57
58
59
60

/// Network events as transmitted to other subsystems, wrapped in their message types.
pub mod network_bridge_event;
pub use network_bridge_event::NetworkBridgeEvent;

61
62
63
64
65
/// Subsystem messages where each message is always bound to a relay parent.
pub trait BoundToRelayParent {
	/// Returns the relay parent this message is bound to.
	fn relay_parent(&self) -> Hash;
}
66

67
/// Messages received by the Candidate Backing subsystem.
68
#[derive(Debug)]
69
pub enum CandidateBackingMessage {
70
71
	/// Requests a set of backable candidates that could be backed in a child of the given
	/// relay-parent, referenced by its hash.
72
	GetBackedCandidates(Hash, Vec<CandidateHash>, oneshot::Sender<Vec<BackedCandidate>>),
73
74
	/// Note that the Candidate Backing subsystem should second the given candidate in the context of the
	/// given relay-parent (ref. by hash). This candidate must be validated.
asynchronous rob's avatar
asynchronous rob committed
75
	Second(Hash, CandidateReceipt, PoV),
76
77
	/// Note a validator's statement about a particular candidate. Disagreements about validity must be escalated
	/// to a broader check by Misbehavior Arbitration. Agreements are simply tallied until a quorum is reached.
78
	Statement(Hash, SignedFullStatement),
79
80
}

81
82
impl BoundToRelayParent for CandidateBackingMessage {
	fn relay_parent(&self) -> Hash {
83
		match self {
84
			Self::GetBackedCandidates(hash, _, _) => *hash,
85
86
			Self::Second(hash, _, _) => *hash,
			Self::Statement(hash, _) => *hash,
87
88
89
90
		}
	}
}

91
/// Blanket error for validation failing for internal reasons.
92
93
#[derive(Debug, Error)]
#[error("Validation failed with {0:?}")]
94
pub struct ValidationFailed(pub String);
95

asynchronous rob's avatar
asynchronous rob committed
96
97
98
99
100
101
102
/// Messages received by the Validation subsystem.
///
/// ## Validation Requests
///
/// Validation requests made to the subsystem should return an error only on internal error.
/// Otherwise, they should return either `Ok(ValidationResult::Valid(_))`
/// or `Ok(ValidationResult::Invalid)`.
103
104
#[derive(Debug)]
pub enum CandidateValidationMessage {
asynchronous rob's avatar
asynchronous rob committed
105
106
	/// Validate a candidate with provided parameters using relay-chain state.
	///
107
	/// This will implicitly attempt to gather the `PersistedValidationData` and `ValidationCode`
asynchronous rob's avatar
asynchronous rob committed
108
109
	/// from the runtime API of the chain, based on the `relay_parent`
	/// of the `CandidateDescriptor`.
110
	///
111
112
	/// This will also perform checking of validation outputs against the acceptance criteria.
	///
113
114
	/// If there is no state available which can provide this data or the core for
	/// the para is not free at the relay-parent, an error is returned.
asynchronous rob's avatar
asynchronous rob committed
115
116
117
	ValidateFromChainState(
		CandidateDescriptor,
		Arc<PoV>,
118
119
		/// Execution timeout
		Duration,
asynchronous rob's avatar
asynchronous rob committed
120
121
122
		oneshot::Sender<Result<ValidationResult, ValidationFailed>>,
	),
	/// Validate a candidate with provided, exhaustive parameters for validation.
123
	///
124
	/// Explicitly provide the `PersistedValidationData` and `ValidationCode` so this can do full
125
126
127
128
129
130
	/// validation without needing to access the state of the relay-chain.
	///
	/// This request doesn't involve acceptance criteria checking, therefore only useful for the
	/// cases where the validity of the candidate is established. This is the case for the typical
	/// use-case: secondary checkers would use this request relying on the full prior checks
	/// performed by the relay-chain.
asynchronous rob's avatar
asynchronous rob committed
131
	ValidateFromExhaustive(
132
		PersistedValidationData,
asynchronous rob's avatar
asynchronous rob committed
133
134
135
		ValidationCode,
		CandidateDescriptor,
		Arc<PoV>,
136
137
		/// Execution timeout
		Duration,
asynchronous rob's avatar
asynchronous rob committed
138
		oneshot::Sender<Result<ValidationResult, ValidationFailed>>,
139
140
141
	),
}

142
143
144
145
impl CandidateValidationMessage {
	/// If the current variant contains the relay parent hash, return it.
	pub fn relay_parent(&self) -> Option<Hash> {
		match self {
146
147
			Self::ValidateFromChainState(_, _, _, _) => None,
			Self::ValidateFromExhaustive(_, _, _, _, _, _) => None,
148
149
150
151
		}
	}
}

152
/// Messages received by the Collator Protocol subsystem.
153
#[derive(Debug, derive_more::From)]
154
155
156
157
158
159
160
161
pub enum CollatorProtocolMessage {
	/// Signal to the collator protocol that it should connect to validators with the expectation
	/// of collating on the given para. This is only expected to be called once, early on, if at all,
	/// and only by the Collation Generation subsystem. As such, it will overwrite the value of
	/// the previous signal.
	///
	/// This should be sent before any `DistributeCollation` message.
	CollateOn(ParaId),
162
163
164
165
	/// Provide a collation to distribute to validators with an optional result sender.
	///
	/// The result sender should be informed when at least one parachain validator seconded the collation. It is also
	/// completely okay to just drop the sender.
166
	DistributeCollation(CandidateReceipt, PoV, Option<oneshot::Sender<CollationSecondedSignal>>),
167
168
169
170
	/// Report a collator as having provided an invalid collation. This should lead to disconnect
	/// and blacklist of the collator.
	ReportCollator(CollatorId),
	/// Get a network bridge update.
171
	#[from]
172
	NetworkBridgeUpdateV1(NetworkBridgeEvent<protocol_v1::CollatorProtocolMessage>),
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
	/// We recommended a particular candidate to be seconded, but it was invalid; penalize the collator.
	///
	/// The hash is the relay parent.
	Invalid(Hash, CandidateReceipt),
	/// The candidate we recommended to be seconded was validated successfully.
	///
	/// The hash is the relay parent.
	Seconded(Hash, SignedFullStatement),
}

impl Default for CollatorProtocolMessage {
	fn default() -> Self {
		Self::CollateOn(Default::default())
	}
}

impl BoundToRelayParent for CollatorProtocolMessage {
	fn relay_parent(&self) -> Hash {
		Default::default()
	}
193
194
}

195
196
197
/// Messages received by the dispute coordinator subsystem.
#[derive(Debug)]
pub enum DisputeCoordinatorMessage {
198
	/// Import statements by validators about a candidate.
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
	///
	/// The subsystem will silently discard ancient statements or sets of only dispute-specific statements for
	/// candidates that are previously unknown to the subsystem. The former is simply because ancient
	/// data is not relevant and the latter is as a DoS prevention mechanism. Both backing and approval
	/// statements already undergo anti-DoS procedures in their respective subsystems, but statements
	/// cast specifically for disputes are not necessarily relevant to any candidate the system is
	/// already aware of and thus present a DoS vector. Our expectation is that nodes will notify each
	/// other of disputes over the network by providing (at least) 2 conflicting statements, of which one is either
	/// a backing or validation statement.
	///
	/// This does not do any checking of the message signature.
	ImportStatements {
		/// The hash of the candidate.
		candidate_hash: CandidateHash,
		/// The candidate receipt itself.
		candidate_receipt: CandidateReceipt,
		/// The session the candidate appears in.
		session: SessionIndex,
		/// Statements, with signatures checked, by validators participating in disputes.
		///
		/// The validator index passed alongside each statement should correspond to the index
		/// of the validator in the set.
		statements: Vec<(SignedDisputeStatement, ValidatorIndex)>,
222
223
224
225
226
227
228
229
230
		/// Inform the requester once we finished importing.
		///
		/// This is:
		/// - we discarded the votes because
		///		- they were ancient or otherwise invalid (result: `InvalidImport`)
		///		- or we were not able to recover availability for an unknown candidate (result:
		///		`InvalidImport`)
		///		- or were known already (in that case the result will still be `ValidImport`)
		/// - or we recorded them because (`ValidImport`)
Denis_P's avatar
Denis_P committed
231
		///		- we cast our own vote already on that dispute
232
233
234
235
		///		- or we have approval votes on that candidate
		///		- or other explicit votes on that candidate already recorded
		///		- or recovered availability for the candidate
		///		- or the imported statements are backing/approval votes, which are always accepted.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
236
		pending_confirmation: oneshot::Sender<ImportStatementsResult>,
237
	},
238
239
240
241
	/// Fetch a list of all recent disputes the co-ordinator is aware of.
	/// These are disputes which have occurred any time in recent sessions,
	/// and which may have already concluded.
	RecentDisputes(oneshot::Sender<Vec<(SessionIndex, CandidateHash)>>),
242
	/// Fetch a list of all active disputes that the coordinator is aware of.
243
	/// These disputes are either unconcluded or recently concluded.
244
245
	ActiveDisputes(oneshot::Sender<Vec<(SessionIndex, CandidateHash)>>),
	/// Get candidate votes for a candidate.
246
247
248
249
	QueryCandidateVotes(
		Vec<(SessionIndex, CandidateHash)>,
		oneshot::Sender<Vec<(SessionIndex, CandidateHash, CandidateVotes)>>,
	),
250
251
252
253
254
255
256
257
258
259
	/// Sign and issue local dispute votes. A value of `true` indicates validity, and `false` invalidity.
	IssueLocalStatement(SessionIndex, CandidateHash, CandidateReceipt, bool),
	/// Determine the highest undisputed block within the given chain, based on where candidates
	/// were included. If even the base block should not be finalized due to a dispute,
	/// then `None` should be returned on the channel.
	///
	/// The block descriptions begin counting upwards from the block after the given `base_number`. The `base_number`
	/// is typically the number of the last finalized block but may be slightly higher. This block
	/// is inevitably going to be finalized so it is not accounted for by this function.
	DetermineUndisputedChain {
260
261
		/// The lowest possible block to vote on.
		base: (BlockNumber, Hash),
262
		/// Descriptions of all the blocks counting upwards from the block after the base number
263
		block_descriptions: Vec<BlockDescription>,
264
265
		/// The block to vote on, might be base in case there is no better.
		tx: oneshot::Sender<(BlockNumber, Hash)>,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
266
	},
267
268
}

269
270
271
272
273
274
/// The result of `DisputeCoordinatorMessage::ImportStatements`.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ImportStatementsResult {
	/// Import was invalid (candidate was not available)  and the sending peer should get banned.
	InvalidImport,
	/// Import was valid and can be confirmed to peer.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
275
	ValidImport,
276
277
}

278
279
280
281
282
283
284
285
286
287
288
/// Messages received by the dispute participation subsystem.
#[derive(Debug)]
pub enum DisputeParticipationMessage {
	/// Validate a candidate for the purposes of participating in a dispute.
	Participate {
		/// The hash of the candidate
		candidate_hash: CandidateHash,
		/// The candidate receipt itself.
		candidate_receipt: CandidateReceipt,
		/// The session the candidate appears in.
		session: SessionIndex,
289
290
		/// The number of validators in the session.
		n_validators: u32,
291
292
293
		/// Give immediate feedback on whether the candidate was available or
		/// not.
		report_availability: oneshot::Sender<bool>,
294
	},
295
296
}

297
298
299
300
301
302
303
304
/// Messages going to the dispute distribution subsystem.
#[derive(Debug)]
pub enum DisputeDistributionMessage {
	/// Tell dispute distribution to distribute an explicit dispute statement to
	/// validators.
	SendDispute(DisputeMessage),
}

305
/// Messages received by the network bridge subsystem.
306
307
#[derive(Debug)]
pub enum NetworkBridgeMessage {
308
	/// Report a peer for their actions.
309
	ReportPeer(PeerId, UnifiedReputationChange),
310

311
312
313
	/// Disconnect a peer from the given peer-set without affecting their reputation.
	DisconnectPeer(PeerId, PeerSet),

314
315
316
317
318
319
	/// Send a message to one or more peers on the validation peer-set.
	SendValidationMessage(Vec<PeerId>, protocol_v1::ValidationProtocol),

	/// Send a message to one or more peers on the collation peer-set.
	SendCollationMessage(Vec<PeerId>, protocol_v1::CollationProtocol),

320
	/// Send a batch of validation messages.
321
322
	///
	/// NOTE: Messages will be processed in order (at least statement distribution relies on this).
323
324
325
	SendValidationMessages(Vec<(Vec<PeerId>, protocol_v1::ValidationProtocol)>),

	/// Send a batch of collation messages.
326
327
	///
	/// NOTE: Messages will be processed in order.
328
329
	SendCollationMessages(Vec<(Vec<PeerId>, protocol_v1::CollationProtocol)>),

330
	/// Send requests via substrate request/response.
331
332
	/// Second parameter, tells what to do if we are not yet connected to the peer.
	SendRequests(Vec<Requests>, IfDisconnected),
333

334
	/// Connect to peers who represent the given `validator_ids`.
335
	///
336
	/// Also ask the network to stay connected to these peers at least
337
338
339
340
341
	/// until a new request is issued.
	///
	/// Because it overrides the previous request, it must be ensured
	/// that `validator_ids` include all peers the subsystems
	/// are interested in (per `PeerSet`).
342
343
344
	///
	/// A caller can learn about validator connections by listening to the
	/// `PeerConnected` events from the network bridge.
345
346
347
	ConnectToValidators {
		/// Ids of the validators to connect to.
		validator_ids: Vec<AuthorityDiscoveryId>,
348
349
		/// The underlying protocol to use for this request.
		peer_set: PeerSet,
350
351
352
		/// Sends back the number of `AuthorityDiscoveryId`s which
		/// authority discovery has failed to resolve.
		failed: oneshot::Sender<usize>,
353
	},
354
355
356
357
358
359
360
361
	/// Alternative to `ConnectToValidators` in case you already know the `Multiaddrs` you want to be
	/// connected to.
	ConnectToResolvedValidators {
		/// Each entry corresponds to the addresses of an already resolved validator.
		validator_addrs: Vec<Vec<Multiaddr>>,
		/// The peer set we want the connection on.
		peer_set: PeerSet,
	},
362
363
364
365
366
367
	/// Inform the distribution subsystems about the new
	/// gossip network topology formed.
	NewGossipTopology {
		/// Ids of our neighbors in the new gossip topology.
		/// We're not necessarily connected to all of them, but we should.
		our_neighbors: HashSet<AuthorityDiscoveryId>,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
368
	},
369
370
}

371
372
373
374
375
impl NetworkBridgeMessage {
	/// If the current variant contains the relay parent hash, return it.
	pub fn relay_parent(&self) -> Option<Hash> {
		match self {
			Self::ReportPeer(_, _) => None,
376
			Self::DisconnectPeer(_, _) => None,
377
378
			Self::SendValidationMessage(_, _) => None,
			Self::SendCollationMessage(_, _) => None,
379
380
			Self::SendValidationMessages(_) => None,
			Self::SendCollationMessages(_) => None,
381
			Self::ConnectToValidators { .. } => None,
382
			Self::ConnectToResolvedValidators { .. } => None,
383
			Self::SendRequests { .. } => None,
384
			Self::NewGossipTopology { .. } => None,
385
386
387
388
		}
	}
}

389
/// Availability Distribution Message.
390
#[derive(Debug)]
391
pub enum AvailabilityDistributionMessage {
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
	/// Instruct availability distribution to fetch a remote PoV.
	///
	/// NOTE: The result of this fetch is not yet locally validated and could be bogus.
	FetchPoV {
		/// The relay parent giving the necessary context.
		relay_parent: Hash,
		/// Validator to fetch the PoV from.
		from_validator: ValidatorIndex,
		/// Candidate hash to fetch the PoV for.
		candidate_hash: CandidateHash,
		/// Expected hash of the PoV, a PoV not matching this hash will be rejected.
		pov_hash: Hash,
		/// Sender for getting back the result of this fetch.
		///
		/// The sender will be canceled if the fetching failed for some reason.
		tx: oneshot::Sender<PoV>,
	},
409
410
}

411
/// Availability Recovery Message.
412
#[derive(Debug, derive_more::From)]
413
414
415
416
417
pub enum AvailabilityRecoveryMessage {
	/// Recover available data from validators on the network.
	RecoverAvailableData(
		CandidateReceipt,
		SessionIndex,
418
		Option<GroupIndex>, // Optional backing group to request from first.
419
420
421
422
		oneshot::Sender<Result<AvailableData, crate::errors::RecoveryError>>,
	),
}

423
/// Bitfield distribution message.
424
#[derive(Debug, derive_more::From)]
425
426
427
428
429
pub enum BitfieldDistributionMessage {
	/// Distribute a bitfield via gossip to other validators.
	DistributeBitfield(Hash, SignedAvailabilityBitfield),

	/// Event from the network bridge.
430
	#[from]
431
	NetworkBridgeUpdateV1(NetworkBridgeEvent<protocol_v1::BitfieldDistributionMessage>),
432
433
}

434
435
436
437
438
impl BitfieldDistributionMessage {
	/// If the current variant contains the relay parent hash, return it.
	pub fn relay_parent(&self) -> Option<Hash> {
		match self {
			Self::DistributeBitfield(hash, _) => Some(*hash),
439
			Self::NetworkBridgeUpdateV1(_) => None,
440
441
442
443
		}
	}
}

444
445
446
447
448
449
/// Bitfield signing message.
///
/// Currently non-instantiable.
#[derive(Debug)]
pub enum BitfieldSigningMessage {}

450
451
452
impl BoundToRelayParent for BitfieldSigningMessage {
	fn relay_parent(&self) -> Hash {
		match *self {}
453
454
455
	}
}

456
/// Availability store subsystem message.
457
#[derive(Debug)]
458
pub enum AvailabilityStoreMessage {
459
	/// Query a `AvailableData` from the AV store.
460
	QueryAvailableData(CandidateHash, oneshot::Sender<Option<AvailableData>>),
461

462
	/// Query whether a `AvailableData` exists within the AV Store.
463
	///
464
	/// This is useful in cases when existence
465
466
	/// matters, but we don't want to necessarily pass around multiple
	/// megabytes of data to get a single bit of information.
467
	QueryDataAvailability(CandidateHash, oneshot::Sender<bool>),
468

469
	/// Query an `ErasureChunk` from the AV store by the candidate hash and validator index.
470
	QueryChunk(CandidateHash, ValidatorIndex, oneshot::Sender<Option<ErasureChunk>>),
471

472
473
474
	/// Query all chunks that we have for the given candidate hash.
	QueryAllChunks(CandidateHash, oneshot::Sender<Vec<ErasureChunk>>),

475
476
477
478
479
	/// Query whether an `ErasureChunk` exists within the AV Store.
	///
	/// This is useful in cases like bitfield signing, when existence
	/// matters, but we don't want to necessarily pass around large
	/// quantities of data to get a single bit of information.
480
	QueryChunkAvailability(CandidateHash, ValidatorIndex, oneshot::Sender<bool>),
481

482
	/// Store an `ErasureChunk` in the AV store.
483
484
	///
	/// Return `Ok(())` if the store operation succeeded, `Err(())` if it failed.
485
486
	StoreChunk {
		/// A hash of the candidate this chunk belongs to.
487
		candidate_hash: CandidateHash,
488
489
490
491
492
		/// The chunk itself.
		chunk: ErasureChunk,
		/// Sending side of the channel to send result to.
		tx: oneshot::Sender<Result<(), ()>>,
	},
493

494
	/// Store a `AvailableData` and all of its chunks in the AV store.
495
496
	///
	/// Return `Ok(())` if the store operation succeeded, `Err(())` if it failed.
497
498
499
500
501
502
503
504
505
506
	StoreAvailableData {
		/// A hash of the candidate this `available_data` belongs to.
		candidate_hash: CandidateHash,
		/// The number of validators in the session.
		n_validators: u32,
		/// The `AvailableData` itself.
		available_data: AvailableData,
		/// Sending side of the channel to send result to.
		tx: oneshot::Sender<Result<(), ()>>,
	},
507
508
}

509
impl AvailabilityStoreMessage {
Denis_P's avatar
Denis_P committed
510
	/// In fact, none of the `AvailabilityStore` messages assume a particular relay parent.
511
512
	pub fn relay_parent(&self) -> Option<Hash> {
		match self {
513
			_ => None,
514
515
516
517
		}
	}
}

Andronik Ordian's avatar
Andronik Ordian committed
518
519
520
521
522
523
524
525
526
/// A response channel for the result of a chain API request.
pub type ChainApiResponseChannel<T> = oneshot::Sender<Result<T, crate::errors::ChainApiError>>;

/// Chain API request subsystem message.
#[derive(Debug)]
pub enum ChainApiMessage {
	/// Request the block number by hash.
	/// Returns `None` if a block with the given hash is not present in the db.
	BlockNumber(Hash, ChainApiResponseChannel<Option<BlockNumber>>),
527
528
529
	/// Request the block header by hash.
	/// Returns `None` if a block with the given hash is not present in the db.
	BlockHeader(Hash, ChainApiResponseChannel<Option<BlockHeader>>),
530
531
532
	/// Get the cumulative weight of the given block, by hash.
	/// If the block or weight is unknown, this returns `None`.
	///
533
	/// Note: this is the weight within the low-level fork-choice rule,
534
535
536
537
	/// not the high-level one implemented in the chain-selection subsystem.
	///
	/// Weight is used for comparing blocks in a fork-choice rule.
	BlockWeight(Hash, ChainApiResponseChannel<Option<BlockWeight>>),
Andronik Ordian's avatar
Andronik Ordian committed
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
	/// Request the finalized block hash by number.
	/// Returns `None` if a block with the given number is not present in the db.
	/// Note: the caller must ensure the block is finalized.
	FinalizedBlockHash(BlockNumber, ChainApiResponseChannel<Option<Hash>>),
	/// Request the last finalized block number.
	/// This request always succeeds.
	FinalizedBlockNumber(ChainApiResponseChannel<BlockNumber>),
	/// Request the `k` ancestors block hashes of a block with the given hash.
	/// The response channel may return a `Vec` of size up to `k`
	/// filled with ancestors hashes with the following order:
	/// `parent`, `grandparent`, ...
	Ancestors {
		/// The hash of the block in question.
		hash: Hash,
		/// The number of ancestors to request.
		k: usize,
554
		/// The response channel.
Andronik Ordian's avatar
Andronik Ordian committed
555
556
557
558
559
560
561
562
563
564
565
		response_channel: ChainApiResponseChannel<Vec<Hash>>,
	},
}

impl ChainApiMessage {
	/// If the current variant contains the relay parent hash, return it.
	pub fn relay_parent(&self) -> Option<Hash> {
		None
	}
}

566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
/// Chain selection subsystem messages
#[derive(Debug)]
pub enum ChainSelectionMessage {
	/// Signal to the chain selection subsystem that a specific block has been approved.
	Approved(Hash),
	/// Request the leaves in descending order by score.
	Leaves(oneshot::Sender<Vec<Hash>>),
	/// Request the best leaf containing the given block in its ancestry. Return `None` if
	/// there is no such leaf.
	BestLeafContaining(Hash, oneshot::Sender<Option<Hash>>),
}

impl ChainSelectionMessage {
	/// If the current variant contains the relay parent hash, return it.
	pub fn relay_parent(&self) -> Option<Hash> {
		// None of the messages, even the ones containing specific
		// block hashes, can be considered to have those blocks as
		// a relay parent.
		match *self {
			ChainSelectionMessage::Approved(_) => None,
			ChainSelectionMessage::Leaves(_) => None,
			ChainSelectionMessage::BestLeafContaining(..) => None,
		}
	}
}

592
/// A sender for the result of a runtime API request.
Andronik Ordian's avatar
Andronik Ordian committed
593
pub type RuntimeApiSender<T> = oneshot::Sender<Result<T, crate::errors::RuntimeApiError>>;
594

595
/// A request to the Runtime API subsystem.
596
#[derive(Debug)]
597
pub enum RuntimeApiRequest {
598
599
	/// Get the next, current and some previous authority discovery set deduplicated.
	Authorities(RuntimeApiSender<Vec<AuthorityDiscoveryId>>),
600
	/// Get the current validator set.
601
602
603
604
605
	Validators(RuntimeApiSender<Vec<ValidatorId>>),
	/// Get the validator groups and group rotation info.
	ValidatorGroups(RuntimeApiSender<(Vec<Vec<ValidatorIndex>>, GroupRotationInfo)>),
	/// Get information on all availability cores.
	AvailabilityCores(RuntimeApiSender<Vec<CoreState>>),
606
	/// Get the persisted validation data for a particular para, taking the given
607
608
	/// `OccupiedCoreAssumption`, which will inform on how the validation data should be computed
	/// if the para currently occupies a core.
609
	PersistedValidationData(
610
611
		ParaId,
		OccupiedCoreAssumption,
612
613
		RuntimeApiSender<Option<PersistedValidationData>>,
	),
614
615
616
	/// Sends back `true` if the validation outputs pass all acceptance criteria checks.
	CheckValidationOutputs(
		ParaId,
617
		polkadot_primitives::v1::CandidateCommitments,
618
619
		RuntimeApiSender<bool>,
	),
620
621
	/// Get the session index that a child of the block will have.
	SessionIndexForChild(RuntimeApiSender<SessionIndex>),
622
623
624
	/// Get the validation code for a para, taking the given `OccupiedCoreAssumption`, which
	/// will inform on how the validation data should be computed if the para currently
	/// occupies a core.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
625
	ValidationCode(ParaId, OccupiedCoreAssumption, RuntimeApiSender<Option<ValidationCode>>),
626
627
628
	/// Get validation code by its hash, either past, current or future code can be returned, as long as state is still
	/// available.
	ValidationCodeByHash(ValidationCodeHash, RuntimeApiSender<Option<ValidationCode>>),
629
	/// Get a the candidate pending availability for a particular parachain by parachain / core index
630
631
632
633
	CandidatePendingAvailability(ParaId, RuntimeApiSender<Option<CommittedCandidateReceipt>>),
	/// Get all events concerning candidates (backing, inclusion, time-out) in the parent of
	/// the block in whose state this request is executed.
	CandidateEvents(RuntimeApiSender<Vec<CandidateEvent>>),
634
635
	/// Get the session info for the given session, if stored.
	SessionInfo(SessionIndex, RuntimeApiSender<Option<SessionInfo>>),
636
	/// Get all the pending inbound messages in the downward message queue for a para.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
637
	DmqContents(ParaId, RuntimeApiSender<Vec<InboundDownwardMessage<BlockNumber>>>),
Sergey Pepyakin's avatar
Sergey Pepyakin committed
638
639
640
641
642
643
	/// Get the contents of all channels addressed to the given recipient. Channels that have no
	/// messages in them are also included.
	InboundHrmpChannelsContents(
		ParaId,
		RuntimeApiSender<BTreeMap<ParaId, Vec<InboundHrmpMessage<BlockNumber>>>>,
	),
644
645
	/// Get information about the BABE epoch the block was included in.
	CurrentBabeEpoch(RuntimeApiSender<BabeEpoch>),
646
647
	/// Get all disputes in relation to a relay parent.
	FetchOnChainVotes(RuntimeApiSender<Option<polkadot_primitives::v1::ScrapedOnChainVotes>>),
648
649
650
}

/// A message to the Runtime API subsystem.
651
#[derive(Debug)]
652
653
654
655
656
pub enum RuntimeApiMessage {
	/// Make a request of the runtime API against the post-state of the given relay-parent.
	Request(Hash, RuntimeApiRequest),
}

657
658
659
660
661
662
663
664
665
impl RuntimeApiMessage {
	/// If the current variant contains the relay parent hash, return it.
	pub fn relay_parent(&self) -> Option<Hash> {
		match self {
			Self::Request(hash, _) => Some(*hash),
		}
	}
}

666
/// Statement distribution message.
667
#[derive(Debug, derive_more::From)]
668
669
670
pub enum StatementDistributionMessage {
	/// We have originated a signed statement in the context of
	/// given relay-parent hash and it should be distributed to other validators.
671
	Share(Hash, SignedFullStatement),
672
	/// Event from the network bridge.
673
	#[from]
674
	NetworkBridgeUpdateV1(NetworkBridgeEvent<protocol_v1::StatementDistributionMessage>),
675
676
}

677
/// This data becomes intrinsics or extrinsics which should be included in a future relay chain block.
678
679
// It needs to be cloneable because multiple potential block authors can request copies.
#[derive(Debug, Clone)]
680
681
682
683
pub enum ProvisionableData {
	/// This bitfield indicates the availability of various candidate blocks.
	Bitfield(Hash, SignedAvailabilityBitfield),
	/// The Candidate Backing subsystem believes that this candidate is valid, pending availability.
684
	BackedCandidate(CandidateReceipt),
685
	/// Misbehavior reports are self-contained proofs of validator misbehavior.
686
	MisbehaviorReport(Hash, ValidatorIndex, Misbehavior),
687
	/// Disputes trigger a broad dispute resolution process.
asynchronous rob's avatar
asynchronous rob committed
688
	Dispute(Hash, ValidatorSignature),
689
690
}

691
692
693
694
695
696
697
698
699
700
/// Inherent data returned by the provisioner
#[derive(Debug, Clone)]
pub struct ProvisionerInherentData {
	/// Signed bitfields.
	pub bitfields: SignedAvailabilityBitfields,
	/// Backed candidates.
	pub backed_candidates: Vec<BackedCandidate>,
	/// Dispute statement sets.
	pub disputes: MultiDisputeStatementSet,
}
701

702
703
704
/// Message to the Provisioner.
///
/// In all cases, the Hash is that of the relay parent.
705
#[derive(Debug)]
706
pub enum ProvisionerMessage {
707
708
709
	/// This message allows external subsystems to request the set of bitfields and backed candidates
	/// associated with a particular potential block hash.
	///
Denis_P's avatar
Denis_P committed
710
711
	/// This is expected to be used by a proposer, to inject that information into the `InherentData`
	/// where it can be assembled into the `ParaInherent`.
712
	RequestInherentData(Hash, oneshot::Sender<ProvisionerInherentData>),
713
	/// This data should become part of a relay chain block
714
	ProvisionableData(Hash, ProvisionableData),
715
716
}

717
718
impl BoundToRelayParent for ProvisionerMessage {
	fn relay_parent(&self) -> Hash {
719
		match self {
720
721
			Self::RequestInherentData(hash, _) => *hash,
			Self::ProvisionableData(hash, _) => *hash,
722
723
724
725
		}
	}
}

726
/// Message to the Collation Generation subsystem.
727
728
729
730
731
732
733
734
735
736
737
738
739
#[derive(Debug)]
pub enum CollationGenerationMessage {
	/// Initialize the collation generation subsystem
	Initialize(CollationGenerationConfig),
}

impl CollationGenerationMessage {
	/// If the current variant contains the relay parent hash, return it.
	pub fn relay_parent(&self) -> Option<Hash> {
		None
	}
}

740
/// The result type of [`ApprovalVotingMessage::CheckAndImportAssignment`] request.
741
#[derive(Debug, Clone, PartialEq, Eq)]
742
743
744
745
746
747
748
749
pub enum AssignmentCheckResult {
	/// The vote was accepted and should be propagated onwards.
	Accepted,
	/// The vote was valid but duplicate and should not be propagated onwards.
	AcceptedDuplicate,
	/// The vote was valid but too far in the future to accept right now.
	TooFarInFuture,
	/// The vote was bad and should be ignored, reporting the peer who propagated it.
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
	Bad(AssignmentCheckError),
}

/// The error result type of [`ApprovalVotingMessage::CheckAndImportAssignment`] request.
#[derive(Error, Debug, Clone, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum AssignmentCheckError {
	#[error("Unknown block: {0:?}")]
	UnknownBlock(Hash),
	#[error("Unknown session index: {0}")]
	UnknownSessionIndex(SessionIndex),
	#[error("Invalid candidate index: {0}")]
	InvalidCandidateIndex(CandidateIndex),
	#[error("Invalid candidate {0}: {1:?}")]
	InvalidCandidate(CandidateIndex, CandidateHash),
	#[error("Invalid cert: {0:?}")]
	InvalidCert(ValidatorIndex),
	#[error("Internal state mismatch: {0:?}, {1:?}")]
	Internal(Hash, CandidateHash),
769
770
771
}

/// The result type of [`ApprovalVotingMessage::CheckAndImportApproval`] request.
772
#[derive(Debug, Clone, PartialEq, Eq)]
773
774
775
776
pub enum ApprovalCheckResult {
	/// The vote was accepted and should be propagated onwards.
	Accepted,
	/// The vote was bad and should be ignored, reporting the peer who propagated it.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
777
	Bad(ApprovalCheckError),
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
}

/// The error result type of [`ApprovalVotingMessage::CheckAndImportApproval`] request.
#[derive(Error, Debug, Clone, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum ApprovalCheckError {
	#[error("Unknown block: {0:?}")]
	UnknownBlock(Hash),
	#[error("Unknown session index: {0}")]
	UnknownSessionIndex(SessionIndex),
	#[error("Invalid candidate index: {0}")]
	InvalidCandidateIndex(CandidateIndex),
	#[error("Invalid validator index: {0:?}")]
	InvalidValidatorIndex(ValidatorIndex),
	#[error("Invalid candidate {0}: {1:?}")]
	InvalidCandidate(CandidateIndex, CandidateHash),
	#[error("Invalid signature: {0:?}")]
	InvalidSignature(ValidatorIndex),
	#[error("No assignment for {0:?}")]
	NoAssignment(ValidatorIndex),
	#[error("Internal state mismatch: {0:?}, {1:?}")]
	Internal(Hash, CandidateHash),
800
801
}

802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
/// Describes a relay-chain block by the para-chain candidates
/// it includes.
#[derive(Clone, Debug)]
pub struct BlockDescription {
	/// The relay-chain block hash.
	pub block_hash: Hash,
	/// The session index of this block.
	pub session: SessionIndex,
	/// The set of para-chain candidates.
	pub candidates: Vec<CandidateHash>,
}

/// Response type to `ApprovalVotingMessage::ApprovedAncestor`.
#[derive(Clone, Debug)]
pub struct HighestApprovedAncestorBlock {
	/// The block hash of the highest viable ancestor.
	pub hash: Hash,
	/// The block number of the highest viable ancestor.
	pub number: BlockNumber,
	/// Block descriptions in the direct path between the
	/// initially provided hash and the highest viable ancestor.
	/// Primarily for use with `DetermineUndisputedChain`.
	/// Must be sorted from lowest to highest block number.
	pub descriptions: Vec<BlockDescription>,
}

828
829
830
831
832
833
834
/// Message to the Approval Voting subsystem.
#[derive(Debug)]
pub enum ApprovalVotingMessage {
	/// Check if the assignment is valid and can be accepted by our view of the protocol.
	/// Should not be sent unless the block hash is known.
	CheckAndImportAssignment(
		IndirectAssignmentCert,
835
		CandidateIndex,
836
837
838
839
840
841
		oneshot::Sender<AssignmentCheckResult>,
	),
	/// Check if the approval vote is valid and can be accepted by our view of the
	/// protocol.
	///
	/// Should not be sent unless the block hash within the indirect vote is known.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
842
	CheckAndImportApproval(IndirectSignedApprovalVote, oneshot::Sender<ApprovalCheckResult>),
843
844
845
846
847
848
849
	/// Returns the highest possible ancestor hash of the provided block hash which is
	/// acceptable to vote on finality for.
	/// The `BlockNumber` provided is the number of the block's ancestor which is the
	/// earliest possible vote.
	///
	/// It can also return the same block hash, if that is acceptable to vote upon.
	/// Return `None` if the input hash is unrecognized.
850
	ApprovedAncestor(Hash, BlockNumber, oneshot::Sender<Option<HighestApprovedAncestorBlock>>),
851
852
853
}

/// Message to the Approval Distribution subsystem.
854
#[derive(Debug, derive_more::From)]
855
856
857
858
859
860
861
862
863
864
865
866
pub enum ApprovalDistributionMessage {
	/// Notify the `ApprovalDistribution` subsystem about new blocks
	/// and the candidates contained within them.
	NewBlocks(Vec<BlockApprovalMeta>),
	/// Distribute an assignment cert from the local validator. The cert is assumed
	/// to be valid, relevant, and for the given relay-parent and validator index.
	DistributeAssignment(IndirectAssignmentCert, CandidateIndex),
	/// Distribute an approval vote for the local validator. The approval vote is assumed to be
	/// valid, relevant, and the corresponding approval already issued.
	/// If not, the subsystem is free to drop the message.
	DistributeApproval(IndirectSignedApprovalVote),
	/// An update from the network bridge.
867
	#[from]
868
869
870
	NetworkBridgeUpdateV1(NetworkBridgeEvent<protocol_v1::ApprovalDistributionMessage>),
}

871
/// Message to the Gossip Support subsystem.
872
873
874
875
876
877
#[derive(Debug, derive_more::From)]
pub enum GossipSupportMessage {
	/// Dummy constructor, so we can receive networking events.
	#[from]
	NetworkBridgeUpdateV1(NetworkBridgeEvent<protocol_v1::GossipSuppportNetworkMessage>),
}