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_api::ProofRecorder;
28use sp_externalities::Extensions;
29use sp_runtime::{
30 traits::{Block as BlockT, HashingFor},
31 Digest,
32};
33
34pub mod block_validation;
35pub mod error;
36mod select_chain;
37
38pub use self::error::Error;
39pub use select_chain::SelectChain;
40pub use sp_inherents::InherentData;
41pub use sp_state_machine::Backend as StateBackend;
42
43/// Block status.
44#[derive(Debug, PartialEq, Eq, Clone)]
45pub enum BlockStatus {
46 /// Added to the import queue.
47 Queued,
48 /// Already in the blockchain and the state is available.
49 InChainWithState,
50 /// In the blockchain, but the state is not available.
51 InChainPruned,
52 /// Block or parent is known to be bad.
53 KnownBad,
54 /// Not in the queue or the blockchain.
55 Unknown,
56}
57
58/// Block data origin.
59#[derive(Debug, PartialEq, Eq, Clone, Copy)]
60pub enum BlockOrigin {
61 /// Genesis block built into the client.
62 Genesis,
63 /// Block is part of the initial sync with the network.
64 NetworkInitialSync,
65 /// Block was broadcasted on the network.
66 NetworkBroadcast,
67 /// Block that was received from the network and validated in the consensus process.
68 ConsensusBroadcast,
69 /// Block that was collated by this node.
70 Own,
71 /// Block was imported from a file.
72 File,
73 /// Block from warp sync proof, already cryptographically verified.
74 ///
75 /// These blocks have been verified through the warp sync protocol's finality proofs
76 /// and are part of the finalized chain. As such, certain consensus verification steps
77 /// can be safely skipped during import. These are the blocks that are used to verify the era
78 /// changes and not the target block to which the node is warp syncing to.
79 WarpSync,
80 /// Block imported during gap sync to fill historical gaps.
81 ///
82 /// Gap sync occurs after warp sync completes, downloading blocks between genesis
83 /// and the warp sync target to fill in the historical chain.
84 GapSync,
85}
86
87/// Environment for a Consensus instance.
88///
89/// Creates proposer instance.
90pub trait Environment<B: BlockT> {
91 /// The proposer type this creates.
92 type Proposer: Proposer<B> + Send + 'static;
93 /// A future that resolves to the proposer.
94 type CreateProposer: Future<Output = Result<Self::Proposer, Self::Error>>
95 + Send
96 + Unpin
97 + 'static;
98 /// Error which can occur upon creation.
99 type Error: From<Error> + Send + Sync + std::error::Error + 'static;
100
101 /// Initialize the proposal logic on top of a specific header. Provide
102 /// the authorities at that header.
103 fn init(&mut self, parent_header: &B::Header) -> Self::CreateProposer;
104}
105
106/// A proposal that is created by a [`Proposer`].
107pub struct Proposal<Block: BlockT> {
108 /// The block that was build.
109 pub block: Block,
110 /// The storage changes while building this block.
111 pub storage_changes: sp_state_machine::StorageChanges<HashingFor<Block>>,
112}
113
114/// Arguments for [`Proposer::propose`].
115pub struct ProposeArgs<B: BlockT> {
116 /// The inherent data to pass to the block production.
117 pub inherent_data: InherentData,
118 /// The inherent digests to include in the produced block.
119 pub inherent_digests: Digest,
120 /// Max duration for building the block.
121 pub max_duration: Duration,
122 /// Optional size limit for the produced block.
123 ///
124 /// When set, block production ends before hitting this limit. The limit includes the storage
125 /// proof, when proof recording is activated.
126 pub block_size_limit: Option<usize>,
127 /// Optional proof recorder for recording storage proofs during block production.
128 ///
129 /// When `Some`, the recorder will be used on block production to record all storage accesses.
130 pub storage_proof_recorder: Option<ProofRecorder<B>>,
131 /// Extra extensions for the runtime environment.
132 pub extra_extensions: Extensions,
133}
134
135impl<B: BlockT> Default for ProposeArgs<B> {
136 fn default() -> Self {
137 Self {
138 inherent_data: Default::default(),
139 inherent_digests: Default::default(),
140 max_duration: Default::default(),
141 block_size_limit: Default::default(),
142 storage_proof_recorder: Default::default(),
143 extra_extensions: Default::default(),
144 }
145 }
146}
147
148/// Logic for a proposer.
149///
150/// This will encapsulate creation and evaluation of proposals at a specific
151/// block.
152///
153/// Proposers are generic over bits of "consensus data" which are engine-specific.
154pub trait Proposer<B: BlockT> {
155 /// Error type which can occur when proposing or evaluating.
156 type Error: From<Error> + Send + Sync + std::error::Error + 'static;
157 /// Future that resolves to a committed proposal with an optional proof.
158 type Proposal: Future<Output = Result<Proposal<B>, Self::Error>> + Send + Unpin + 'static;
159
160 /// Create a proposal.
161 ///
162 /// Takes a [`ProposeArgs`] struct containing all the necessary parameters for block production
163 /// including inherent data, digests, duration limits, storage proof recorder, and extensions.
164 ///
165 /// # Return
166 ///
167 /// Returns a future that resolves to a [`Proposal`] or to [`Error`].
168 fn propose(self, args: ProposeArgs<B>) -> Self::Proposal;
169}
170
171/// An oracle for when major synchronization work is being undertaken.
172///
173/// Generally, consensus authoring work isn't undertaken while well behind
174/// the head of the chain.
175pub trait SyncOracle {
176 /// Whether the synchronization service is undergoing major sync.
177 /// Returns true if so.
178 fn is_major_syncing(&self) -> bool;
179 /// Whether the synchronization service is offline.
180 /// Returns true if so.
181 fn is_offline(&self) -> bool;
182}
183
184/// A synchronization oracle for when there is no network.
185#[derive(Clone, Copy, Debug)]
186pub struct NoNetwork;
187
188impl SyncOracle for NoNetwork {
189 fn is_major_syncing(&self) -> bool {
190 false
191 }
192 fn is_offline(&self) -> bool {
193 false
194 }
195}
196
197impl<T> SyncOracle for Arc<T>
198where
199 T: ?Sized,
200 T: SyncOracle,
201{
202 fn is_major_syncing(&self) -> bool {
203 T::is_major_syncing(self)
204 }
205
206 fn is_offline(&self) -> bool {
207 T::is_offline(self)
208 }
209}