sc_subspace_sync_common/
snap_sync_engine.rs

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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
// 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/>.

//! `SyncingEngine` is the actor responsible for syncing Substrate chain
//! to tip and keep the blockchain up to date with network updates.

use futures::channel::oneshot;
use futures::StreamExt;
use sc_client_api::ProofProvider;
use sc_consensus::IncomingBlock;
use sc_network::types::ProtocolName;
use sc_network::{OutboundFailure, PeerId, RequestFailure};
use sc_network_sync::pending_responses::{PendingResponses, ResponseEvent};
use sc_network_sync::service::network::NetworkServiceHandle;
use sc_network_sync::state_request_handler::generate_protocol_name;
use sc_network_sync::strategy::state::StateStrategy;
use sc_network_sync::strategy::SyncingAction;
use sc_network_sync::types::BadPeer;
use sp_blockchain::{Error as ClientError, HeaderBackend};
use sp_runtime::traits::{Block as BlockT, NumberFor};
use std::sync::Arc;
use tracing::{debug, trace, warn};

mod rep {
    use sc_network::ReputationChange as Rep;
    /// Peer is on unsupported protocol version.
    pub(super) const BAD_PROTOCOL: Rep = Rep::new_fatal("Unsupported protocol");
    /// Reputation change when a peer refuses a request.
    pub(super) const REFUSED: Rep = Rep::new(-(1 << 10), "Request refused");
    /// Reputation change when a peer doesn't respond in time to our messages.
    pub(super) const TIMEOUT: Rep = Rep::new(-(1 << 10), "Request timeout");
}

pub struct SnapSyncingEngine<'a, Block>
where
    Block: BlockT,
{
    /// Syncing strategy
    strategy: StateStrategy<Block>,
    /// Pending responses
    pending_responses: PendingResponses,
    block_announces_protocol_name: ProtocolName,
    network_service_handle: &'a NetworkServiceHandle,
}

impl<'a, Block> SnapSyncingEngine<'a, Block>
where
    Block: BlockT,
{
    pub fn new<Client>(
        client: Arc<Client>,
        fork_id: Option<&str>,
        target_header: Block::Header,
        skip_proof: bool,
        current_sync_peer: (PeerId, NumberFor<Block>),
        network_service_handle: &'a NetworkServiceHandle,
    ) -> Result<Self, ClientError>
    where
        Client: HeaderBackend<Block> + ProofProvider<Block> + Send + Sync + 'static,
    {
        let genesis_hash = client.info().genesis_hash;
        let block_announces_protocol_name = ProtocolName::from(if let Some(fork_id) = fork_id {
            format!(
                "/{}/{}/transactions/1",
                array_bytes::bytes2hex("", genesis_hash),
                fork_id
            )
        } else {
            format!(
                "/{}/transactions/1",
                array_bytes::bytes2hex("", genesis_hash)
            )
        });

        // Initialize syncing strategy.
        let strategy = StateStrategy::new(
            client,
            target_header,
            // We only care about the state, this value is just forwarded back into block to
            // import that is thrown away below
            None,
            // We only care about the state, this value is just forwarded back into block to
            // import that is thrown away below
            None,
            skip_proof,
            vec![current_sync_peer].into_iter(),
            ProtocolName::from(generate_protocol_name(genesis_hash, fork_id)),
        );

        Ok(Self {
            strategy,
            pending_responses: PendingResponses::new(),
            block_announces_protocol_name,
            network_service_handle,
        })
    }

    // Downloads state and returns incoming block with state pre-populated and ready for importing
    pub async fn download_state(mut self) -> Result<IncomingBlock<Block>, ClientError> {
        debug!("Starting state downloading");

        loop {
            // Process actions requested by a syncing strategy.
            let mut actions = self
                .strategy
                .actions(self.network_service_handle)
                .peekable();
            if actions.peek().is_none() {
                return Err(ClientError::Backend(
                    "Sync state download failed: no further actions".into(),
                ));
            }

            for action in actions {
                match action {
                    SyncingAction::StartRequest {
                        peer_id,
                        key,
                        request,
                        // State sync doesn't use this
                        remove_obsolete: _,
                    } => {
                        self.pending_responses.insert(peer_id, key, request);
                    }
                    SyncingAction::CancelRequest { .. } => {
                        return Err(ClientError::Application(
                            "Unexpected SyncingAction::CancelRequest".into(),
                        ));
                    }
                    SyncingAction::DropPeer(BadPeer(peer_id, rep)) => {
                        self.pending_responses
                            .remove(peer_id, StateStrategy::<Block>::STRATEGY_KEY);

                        trace!(%peer_id, "Peer dropped: {rep:?}");
                    }
                    SyncingAction::ImportBlocks { blocks, .. } => {
                        return blocks.into_iter().next().ok_or_else(|| {
                            ClientError::Application(
                                "SyncingAction::ImportBlocks didn't contain any blocks to import"
                                    .into(),
                            )
                        });
                    }
                    SyncingAction::ImportJustifications { .. } => {
                        return Err(ClientError::Application(
                            "Unexpected SyncingAction::ImportJustifications".into(),
                        ));
                    }
                    SyncingAction::Finished => {
                        return Err(ClientError::Backend(
                            "Sync state finished without blocks to import".into(),
                        ));
                    }
                }
            }

            let response_event = self.pending_responses.select_next_some().await;
            self.process_response_event(response_event);
        }
    }

    fn process_response_event(&mut self, response_event: ResponseEvent) {
        let ResponseEvent {
            peer_id,
            key: _,
            response: response_result,
        } = response_event;

        match response_result {
            Ok(Ok((response, _protocol_name))) => {
                let Ok(response) = response.downcast::<Vec<u8>>() else {
                    warn!("Failed to downcast state response");
                    debug_assert!(false);
                    return;
                };

                self.strategy.on_state_response(&peer_id, *response);
            }
            Ok(Err(e)) => {
                debug!("Request to peer {peer_id:?} failed: {e:?}.");

                match e {
                    RequestFailure::Network(OutboundFailure::Timeout) => {
                        self.network_service_handle
                            .report_peer(peer_id, rep::TIMEOUT);
                        self.network_service_handle
                            .disconnect_peer(peer_id, self.block_announces_protocol_name.clone());
                    }
                    RequestFailure::Network(OutboundFailure::UnsupportedProtocols) => {
                        self.network_service_handle
                            .report_peer(peer_id, rep::BAD_PROTOCOL);
                        self.network_service_handle
                            .disconnect_peer(peer_id, self.block_announces_protocol_name.clone());
                    }
                    RequestFailure::Network(OutboundFailure::DialFailure) => {
                        self.network_service_handle
                            .disconnect_peer(peer_id, self.block_announces_protocol_name.clone());
                    }
                    RequestFailure::Refused => {
                        self.network_service_handle
                            .report_peer(peer_id, rep::REFUSED);
                        self.network_service_handle
                            .disconnect_peer(peer_id, self.block_announces_protocol_name.clone());
                    }
                    RequestFailure::Network(OutboundFailure::ConnectionClosed)
                    | RequestFailure::NotConnected => {
                        self.network_service_handle
                            .disconnect_peer(peer_id, self.block_announces_protocol_name.clone());
                    }
                    RequestFailure::UnknownProtocol => {
                        debug_assert!(false, "Block request protocol should always be known.");
                    }
                    RequestFailure::Obsolete => {
                        debug_assert!(
                            false,
                            "Can not receive `RequestFailure::Obsolete` after dropping the \
                            response receiver.",
                        );
                    }
                }
            }
            Err(oneshot::Canceled) => {
                trace!("Request to peer {peer_id:?} failed due to oneshot being canceled.");
                self.network_service_handle
                    .disconnect_peer(peer_id, self.block_announces_protocol_name.clone());
            }
        }
    }
}