sp_consensus/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Common utilities for building and using consensus engines in substrate.
19//!
20//! Much of this crate is _unstable_ and thus the API is likely to undergo
21//! change. Implementors of traits should not rely on the interfaces to remain
22//! the same.
23
24use std::{sync::Arc, time::Duration};
25
26use futures::prelude::*;
27use sp_runtime::{
28	traits::{Block as BlockT, HashingFor},
29	Digest,
30};
31use sp_state_machine::StorageProof;
32
33pub mod block_validation;
34pub mod error;
35mod select_chain;
36
37pub use self::error::Error;
38pub use select_chain::SelectChain;
39pub use sp_inherents::InherentData;
40pub use sp_state_machine::Backend as StateBackend;
41
42/// Block status.
43#[derive(Debug, PartialEq, Eq, Clone)]
44pub enum BlockStatus {
45	/// Added to the import queue.
46	Queued,
47	/// Already in the blockchain and the state is available.
48	InChainWithState,
49	/// In the blockchain, but the state is not available.
50	InChainPruned,
51	/// Block or parent is known to be bad.
52	KnownBad,
53	/// Not in the queue or the blockchain.
54	Unknown,
55}
56
57/// Block data origin.
58#[derive(Debug, PartialEq, Eq, Clone, Copy)]
59pub enum BlockOrigin {
60	/// Genesis block built into the client.
61	Genesis,
62	/// Block is part of the initial sync with the network.
63	NetworkInitialSync,
64	/// Block was broadcasted on the network.
65	NetworkBroadcast,
66	/// Block that was received from the network and validated in the consensus process.
67	ConsensusBroadcast,
68	/// Block that was collated by this node.
69	Own,
70	/// Block was imported from a file.
71	File,
72}
73
74/// Environment for a Consensus instance.
75///
76/// Creates proposer instance.
77pub trait Environment<B: BlockT> {
78	/// The proposer type this creates.
79	type Proposer: Proposer<B> + Send + 'static;
80	/// A future that resolves to the proposer.
81	type CreateProposer: Future<Output = Result<Self::Proposer, Self::Error>>
82		+ Send
83		+ Unpin
84		+ 'static;
85	/// Error which can occur upon creation.
86	type Error: From<Error> + std::error::Error + 'static;
87
88	/// Initialize the proposal logic on top of a specific header. Provide
89	/// the authorities at that header.
90	fn init(&mut self, parent_header: &B::Header) -> Self::CreateProposer;
91}
92
93/// A proposal that is created by a [`Proposer`].
94pub struct Proposal<Block: BlockT, Proof> {
95	/// The block that was build.
96	pub block: Block,
97	/// Proof that was recorded while building the block.
98	pub proof: Proof,
99	/// The storage changes while building this block.
100	pub storage_changes: sp_state_machine::StorageChanges<HashingFor<Block>>,
101}
102
103/// Error that is returned when [`ProofRecording`] requested to record a proof,
104/// but no proof was recorded.
105#[derive(Debug, thiserror::Error)]
106#[error("Proof should be recorded, but no proof was provided.")]
107pub struct NoProofRecorded;
108
109/// A trait to express the state of proof recording on type system level.
110///
111/// This is used by [`Proposer`] to signal if proof recording is enabled. This can be used by
112/// downstream users of the [`Proposer`] trait to enforce that proof recording is activated when
113/// required. The only two implementations of this trait are [`DisableProofRecording`] and
114/// [`EnableProofRecording`].
115///
116/// This trait is sealed and can not be implemented outside of this crate!
117pub trait ProofRecording: Send + Sync + private::Sealed + 'static {
118	/// The proof type that will be used internally.
119	type Proof: Send + Sync + 'static;
120	/// Is proof recording enabled?
121	const ENABLED: bool;
122	/// Convert the given `storage_proof` into [`Self::Proof`].
123	///
124	/// Internally Substrate uses `Option<StorageProof>` to express the both states of proof
125	/// recording (for now) and as [`Self::Proof`] is some different type, we need to provide a
126	/// function to convert this value.
127	///
128	/// If the proof recording was requested, but `None` is given, this will return
129	/// `Err(NoProofRecorded)`.
130	fn into_proof(storage_proof: Option<StorageProof>) -> Result<Self::Proof, NoProofRecorded>;
131}
132
133/// Express that proof recording is disabled.
134///
135/// For more information see [`ProofRecording`].
136pub struct DisableProofRecording;
137
138impl ProofRecording for DisableProofRecording {
139	type Proof = ();
140	const ENABLED: bool = false;
141
142	fn into_proof(_: Option<StorageProof>) -> Result<Self::Proof, NoProofRecorded> {
143		Ok(())
144	}
145}
146
147/// Express that proof recording is enabled.
148///
149/// For more information see [`ProofRecording`].
150pub struct EnableProofRecording;
151
152impl ProofRecording for EnableProofRecording {
153	type Proof = sp_state_machine::StorageProof;
154	const ENABLED: bool = true;
155
156	fn into_proof(proof: Option<StorageProof>) -> Result<Self::Proof, NoProofRecorded> {
157		proof.ok_or(NoProofRecorded)
158	}
159}
160
161/// Provides `Sealed` trait to prevent implementing trait [`ProofRecording`] outside of this crate.
162mod private {
163	/// Special trait that prevents the implementation of [`super::ProofRecording`] outside of this
164	/// crate.
165	pub trait Sealed {}
166
167	impl Sealed for super::DisableProofRecording {}
168	impl Sealed for super::EnableProofRecording {}
169}
170
171/// Logic for a proposer.
172///
173/// This will encapsulate creation and evaluation of proposals at a specific
174/// block.
175///
176/// Proposers are generic over bits of "consensus data" which are engine-specific.
177pub trait Proposer<B: BlockT> {
178	/// Error type which can occur when proposing or evaluating.
179	type Error: From<Error> + std::error::Error + 'static;
180	/// Future that resolves to a committed proposal with an optional proof.
181	type Proposal: Future<Output = Result<Proposal<B, Self::Proof>, Self::Error>>
182		+ Send
183		+ Unpin
184		+ 'static;
185	/// The supported proof recording by the implementor of this trait. See [`ProofRecording`]
186	/// for more information.
187	type ProofRecording: self::ProofRecording<Proof = Self::Proof> + Send + Sync + 'static;
188	/// The proof type used by [`Self::ProofRecording`].
189	type Proof: Send + Sync + 'static;
190
191	/// Create a proposal.
192	///
193	/// Gets the `inherent_data` and `inherent_digests` as input for the proposal. Additionally
194	/// a maximum duration for building this proposal is given. If building the proposal takes
195	/// longer than this maximum, the proposal will be very likely discarded.
196	///
197	/// If `block_size_limit` is given, the proposer should push transactions until the block size
198	/// limit is hit. Depending on the `finalize_block` implementation of the runtime, it probably
199	/// incorporates other operations (that are happening after the block limit is hit). So,
200	/// when the block size estimation also includes a proof that is recorded alongside the block
201	/// production, the proof can still grow. This means that the `block_size_limit` should not be
202	/// the hard limit of what is actually allowed.
203	///
204	/// # Return
205	///
206	/// Returns a future that resolves to a [`Proposal`] or to [`Error`].
207	fn propose(
208		self,
209		inherent_data: InherentData,
210		inherent_digests: Digest,
211		max_duration: Duration,
212		block_size_limit: Option<usize>,
213	) -> Self::Proposal;
214}
215
216/// An oracle for when major synchronization work is being undertaken.
217///
218/// Generally, consensus authoring work isn't undertaken while well behind
219/// the head of the chain.
220pub trait SyncOracle {
221	/// Whether the synchronization service is undergoing major sync.
222	/// Returns true if so.
223	fn is_major_syncing(&self) -> bool;
224	/// Whether the synchronization service is offline.
225	/// Returns true if so.
226	fn is_offline(&self) -> bool;
227}
228
229/// A synchronization oracle for when there is no network.
230#[derive(Clone, Copy, Debug)]
231pub struct NoNetwork;
232
233impl SyncOracle for NoNetwork {
234	fn is_major_syncing(&self) -> bool {
235		false
236	}
237	fn is_offline(&self) -> bool {
238		false
239	}
240}
241
242impl<T> SyncOracle for Arc<T>
243where
244	T: ?Sized,
245	T: SyncOracle,
246{
247	fn is_major_syncing(&self) -> bool {
248		T::is_major_syncing(self)
249	}
250
251	fn is_offline(&self) -> bool {
252		T::is_offline(self)
253	}
254}