lib.rs 7.29 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
// 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/>.

//! Primitive types used on the node-side.
//!
//! Unlike the `polkadot-primitives` crate, these primitives are only used on the node-side,
//! not shared between the node and the runtime. This crate builds on top of the primitives defined
//! there.

23
24
#![deny(missing_docs)]

25
use futures::Future;
26
use parity_scale_codec::{Decode, Encode};
asynchronous rob's avatar
asynchronous rob committed
27
use polkadot_primitives::v1::{
28
29
30
	CandidateCommitments, CandidateHash, CollatorPair, CommittedCandidateReceipt, CompactStatement,
	EncodeAs, Hash, HeadData, Id as ParaId, OutboundHrmpMessage, PersistedValidationData, PoV,
	Signed, UpwardMessage, ValidationCode,
31
};
32
use std::pin::Pin;
33

34
pub use sp_core::traits::SpawnNamed;
35
36
37
pub use sp_consensus_babe::{
	Epoch as BabeEpoch, BabeEpochConfiguration, AllowedSlots as BabeAllowedSlots,
};
38

asynchronous rob's avatar
asynchronous rob committed
39
40
pub mod approval;

41
/// A statement, where the candidate receipt is included in the `Seconded` variant.
asynchronous rob's avatar
asynchronous rob committed
42
43
44
45
46
///
/// This is the committed candidate receipt instead of the bare candidate receipt. As such,
/// it gives access to the commitments to validators who have not executed the candidate. This
/// is necessary to allow a block-producing validator to include candidates from outside of the para
/// it is assigned to.
47
#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
48
49
pub enum Statement {
	/// A statement that a validator seconds a candidate.
50
	#[codec(index = 1)]
asynchronous rob's avatar
asynchronous rob committed
51
	Seconded(CommittedCandidateReceipt),
52
	/// A statement that a validator has deemed a candidate valid.
53
	#[codec(index = 2)]
54
	Valid(CandidateHash),
55
	/// A statement that a validator has deemed a candidate invalid.
56
	#[codec(index = 3)]
57
	Invalid(CandidateHash),
58
59
}

60
impl Statement {
61
62
63
64
65
66
67
68
69
70
71
	/// Get the candidate hash referenced by this statement.
	///
	/// If this is a `Statement::Seconded`, this does hash the candidate receipt, which may be expensive
	/// for large candidates.
	pub fn candidate_hash(&self) -> CandidateHash {
		match *self {
			Statement::Valid(ref h) | Statement::Invalid(ref h) => *h,
			Statement::Seconded(ref c) => c.hash(),
		}
	}

asynchronous rob's avatar
asynchronous rob committed
72
73
	/// Transform this statement into its compact version, which references only the hash
	/// of the candidate.
74
75
	pub fn to_compact(&self) -> CompactStatement {
		match *self {
76
			Statement::Seconded(ref c) => CompactStatement::Seconded(c.hash()),
77
78
79
80
81
82
			Statement::Valid(hash) => CompactStatement::Valid(hash),
			Statement::Invalid(hash) => CompactStatement::Invalid(hash),
		}
	}
}

83
84
85
86
87
88
impl From<&'_ Statement> for CompactStatement {
	fn from(stmt: &Statement) -> Self {
		stmt.to_compact()
	}
}

89
90
impl EncodeAs<CompactStatement> for Statement {
	fn encode_as(&self) -> Vec<u8> {
91
		self.to_compact().encode()
92
93
94
95
96
97
	}
}

/// A statement, the corresponding signature, and the index of the sender.
///
/// Signing context and validator set should be apparent from context.
98
99
100
101
///
/// This statement is "full" in the sense that the `Seconded` variant includes the candidate receipt.
/// Only the compact `SignedStatement` is suitable for submission to the chain.
pub type SignedFullStatement = Signed<Statement, CompactStatement>;
102

103
104
105
106
107
/// Candidate invalidity details
#[derive(Debug)]
pub enum InvalidCandidate {
	/// Failed to execute.`validate_block`. This includes function panicking.
	ExecutionError(String),
108
109
	/// Validation outputs check doesn't pass.
	InvalidOutputs,
110
111
112
113
114
115
116
117
118
119
120
121
122
123
	/// Execution timeout.
	Timeout,
	/// Validation input is over the limit.
	ParamsTooLarge(u64),
	/// Code size is over the limit.
	CodeTooLarge(u64),
	/// Validation function returned invalid data.
	BadReturn,
	/// Invalid relay chain parent.
	BadParent,
	/// POV hash does not match.
	HashMismatch,
	/// Bad collator signature.
	BadSignature,
124
125
	/// Para head hash does not match.
	ParaHeadHashMismatch,
126
127
}

128
129
130
/// Result of the validation of the candidate.
#[derive(Debug)]
pub enum ValidationResult {
131
132
	/// Candidate is valid. The validation process yields these outputs and the persisted validation
	/// data used to form inputs.
133
	Valid(CandidateCommitments, PersistedValidationData),
134
	/// Candidate is invalid.
135
	Invalid(InvalidCandidate),
136
137
}

138
139
140
141
142
143
144
/// The output of a collator.
///
/// This differs from `CandidateCommitments` in two ways:
///
/// - does not contain the erasure root; that's computed at the Polkadot level, not at Cumulus
/// - contains a proof of validity.
#[derive(Clone, Encode, Decode)]
Sergey Pepyakin's avatar
Sergey Pepyakin committed
145
pub struct Collation<BlockNumber = polkadot_primitives::v1::BlockNumber> {
146
147
	/// Messages destined to be interpreted by the Relay chain itself.
	pub upward_messages: Vec<UpwardMessage>,
Sergey Pepyakin's avatar
Sergey Pepyakin committed
148
149
	/// The horizontal messages sent by the parachain.
	pub horizontal_messages: Vec<OutboundHrmpMessage<ParaId>>,
150
151
152
153
	/// New validation code.
	pub new_validation_code: Option<ValidationCode>,
	/// The head-data produced as a result of execution.
	pub head_data: HeadData,
154
	/// Proof to verify the state transition of the parachain.
155
	pub proof_of_validity: PoV,
156
157
	/// The number of messages processed from the DMQ.
	pub processed_downward_messages: u32,
Sergey Pepyakin's avatar
Sergey Pepyakin committed
158
159
	/// The mark which specifies the block number up to which all inbound HRMP messages are processed.
	pub hrmp_watermark: BlockNumber,
160
161
}

162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/// Result of the [`CollatorFn`] invocation.
pub struct CollationResult {
	/// The collation that was build.
	pub collation: Collation,
	/// An optional result sender that should be informed about a successfully seconded collation.
	///
	/// There is no guarantee that this sender is informed ever about any result, it is completly okay to just drop it.
	/// However, if it is called, it should be called with the signed statement of a parachain validator seconding the
	/// collation.
	pub result_sender: Option<futures::channel::oneshot::Sender<SignedFullStatement>>,
}

impl CollationResult {
	/// Convert into the inner values.
	pub fn into_inner(self) -> (Collation, Option<futures::channel::oneshot::Sender<SignedFullStatement>>) {
		(self.collation, self.result_sender)
	}
}

Sergey Pepyakin's avatar
Sergey Pepyakin committed
181
182
/// Collation function.
///
183
184
185
186
/// Will be called with the hash of the relay chain block the parachain block should be build on and the
/// [`ValidationData`] that provides information about the state of the parachain on the relay chain.
///
/// Returns an optional [`CollationResult`].
Sergey Pepyakin's avatar
Sergey Pepyakin committed
187
pub type CollatorFn = Box<
188
	dyn Fn(Hash, &PersistedValidationData) -> Pin<Box<dyn Future<Output = Option<CollationResult>> + Send>>
Sergey Pepyakin's avatar
Sergey Pepyakin committed
189
190
191
192
		+ Send
		+ Sync,
>;

193
194
195
196
/// Configuration for the collation generator
pub struct CollationGenerationConfig {
	/// Collator's authentication key, so it can sign things.
	pub key: CollatorPair,
Sergey Pepyakin's avatar
Sergey Pepyakin committed
197
198
	/// Collation function. See [`CollatorFn`] for more details.
	pub collator: CollatorFn,
199
200
201
202
203
204
205
206
207
	/// The parachain that this collator collates for
	pub para_id: ParaId,
}

impl std::fmt::Debug for CollationGenerationConfig {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "CollationGenerationConfig {{ ... }}")
	}
}