1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program 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.
// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
//! [`SyncingStrategy`] defines an interface [`crate::engine::SyncingEngine`] uses as a specific
//! syncing algorithm.
//!
//! A few different strategies are provided by Substrate out of the box with custom strategies
//! possible too.
pub mod chain_sync;
mod disconnected_peers;
pub mod polkadot;
pub mod state;
pub mod state_sync;
pub mod warp;
use crate::{
pending_responses::ResponseFuture,
service::network::NetworkServiceHandle,
types::{BadPeer, SyncStatus},
};
use sc_consensus::{BlockImportError, BlockImportStatus, IncomingBlock};
use sc_network::ProtocolName;
use sc_network_common::sync::message::BlockAnnounce;
use sc_network_types::PeerId;
use sp_blockchain::Error as ClientError;
use sp_consensus::BlockOrigin;
use sp_runtime::{
traits::{Block as BlockT, NumberFor},
Justifications,
};
use std::any::Any;
/// Syncing strategy for syncing engine to use
pub trait SyncingStrategy<B: BlockT>: Send
where
B: BlockT,
{
/// Notify syncing state machine that a new sync peer has connected.
fn add_peer(&mut self, peer_id: PeerId, best_hash: B::Hash, best_number: NumberFor<B>);
/// Notify that a sync peer has disconnected.
fn remove_peer(&mut self, peer_id: &PeerId);
/// Submit a validated block announcement.
///
/// Returns new best hash & best number of the peer if they are updated.
#[must_use]
fn on_validated_block_announce(
&mut self,
is_best: bool,
peer_id: PeerId,
announce: &BlockAnnounce<B::Header>,
) -> Option<(B::Hash, NumberFor<B>)>;
/// Configure an explicit fork sync request in case external code has detected that there is a
/// stale fork missing.
///
/// Note that this function should not be used for recent blocks.
/// Sync should be able to download all the recent forks normally.
///
/// Passing empty `peers` set effectively removes the sync request.
fn set_sync_fork_request(&mut self, peers: Vec<PeerId>, hash: &B::Hash, number: NumberFor<B>);
/// Request extra justification.
fn request_justification(&mut self, hash: &B::Hash, number: NumberFor<B>);
/// Clear extra justification requests.
fn clear_justification_requests(&mut self);
/// Report a justification import (successful or not).
fn on_justification_import(&mut self, hash: B::Hash, number: NumberFor<B>, success: bool);
/// Process generic response.
///
/// Strategy has to create opaque response and should be to downcast it back into concrete type
/// internally. Failure to downcast is an implementation bug.
fn on_generic_response(
&mut self,
peer_id: &PeerId,
key: StrategyKey,
protocol_name: ProtocolName,
response: Box<dyn Any + Send>,
);
/// A batch of blocks that have been processed, with or without errors.
///
/// Call this when a batch of blocks that have been processed by the import queue, with or
/// without errors.
fn on_blocks_processed(
&mut self,
imported: usize,
count: usize,
results: Vec<(Result<BlockImportStatus<NumberFor<B>>, BlockImportError>, B::Hash)>,
);
/// Notify a syncing strategy that a block has been finalized.
fn on_block_finalized(&mut self, hash: &B::Hash, number: NumberFor<B>);
/// Inform sync about a new best imported block.
fn update_chain_info(&mut self, best_hash: &B::Hash, best_number: NumberFor<B>);
// Are we in major sync mode?
fn is_major_syncing(&self) -> bool;
/// Get the number of peers known to the syncing strategy.
fn num_peers(&self) -> usize;
/// Returns the current sync status.
fn status(&self) -> SyncStatus<B>;
/// Get the total number of downloaded blocks.
fn num_downloaded_blocks(&self) -> usize;
/// Get an estimate of the number of parallel sync requests.
fn num_sync_requests(&self) -> usize;
/// Get actions that should be performed by the owner on the strategy's behalf
#[must_use]
fn actions(
&mut self,
// TODO: Consider making this internal property of the strategy
network_service: &NetworkServiceHandle,
) -> Result<Vec<SyncingAction<B>>, ClientError>;
}
/// The key identifying a specific strategy for responses routing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct StrategyKey(&'static str);
impl StrategyKey {
/// Instantiate opaque strategy key.
pub const fn new(key: &'static str) -> Self {
Self(key)
}
}
pub enum SyncingAction<B: BlockT> {
/// Start request to peer.
StartRequest {
peer_id: PeerId,
key: StrategyKey,
request: ResponseFuture,
// Whether to remove obsolete pending responses.
remove_obsolete: bool,
},
/// Drop stale request.
CancelRequest { peer_id: PeerId, key: StrategyKey },
/// Peer misbehaved. Disconnect, report it and cancel any requests to it.
DropPeer(BadPeer),
/// Import blocks.
ImportBlocks { origin: BlockOrigin, blocks: Vec<IncomingBlock<B>> },
/// Import justifications.
ImportJustifications {
peer_id: PeerId,
hash: B::Hash,
number: NumberFor<B>,
justifications: Justifications,
},
/// Strategy finished. Nothing to do, this is handled by `PolkadotSyncingStrategy`.
Finished,
}
impl<B: BlockT> SyncingAction<B> {
/// Returns `true` if the syncing action has completed.
pub fn is_finished(&self) -> bool {
matches!(self, SyncingAction::Finished)
}
#[cfg(test)]
pub(crate) fn name(&self) -> &'static str {
match self {
Self::StartRequest { .. } => "StartRequest",
Self::CancelRequest { .. } => "CancelRequest",
Self::DropPeer(_) => "DropPeer",
Self::ImportBlocks { .. } => "ImportBlocks",
Self::ImportJustifications { .. } => "ImportJustifications",
Self::Finished => "Finished",
}
}
}