• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tari-project / tari / 17033178607

18 Aug 2025 06:45AM UTC coverage: 54.49% (-0.007%) from 54.497%
17033178607

push

github

stringhandler
Merge branch 'development' of github.com:tari-project/tari into odev

971 of 2923 new or added lines in 369 files covered. (33.22%)

5804 existing lines in 173 files now uncovered.

76688 of 140739 relevant lines covered (54.49%)

193850.18 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/base_layer/core/src/base_node/sync/header_sync/synchronizer.rs
1
//  Copyright 2020, The Tari Project
2
//
3
//  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
4
//  following conditions are met:
5
//
6
//  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
7
//  disclaimer.
8
//
9
//  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
10
//  following disclaimer in the documentation and/or other materials provided with the distribution.
11
//
12
//  3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
13
//  products derived from this software without specific prior written permission.
14
//
15
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
16
//  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17
//  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
18
//  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19
//  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
20
//  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
21
//  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22
use std::{
23
    convert::TryFrom,
24
    sync::Arc,
25
    time::{Duration, Instant},
26
};
27

28
use futures::StreamExt;
29
use log::*;
30
use primitive_types::U512;
31
use tari_common_types::{chain_metadata::ChainMetadata, types::HashOutput};
32
use tari_comms::{
33
    connectivity::ConnectivityRequester,
34
    peer_manager::NodeId,
35
    protocol::rpc::{RpcClient, RpcError},
36
    PeerConnection,
37
};
38
use tari_utilities::hex::Hex;
39

40
pub(crate) use super::{validator::BlockHeaderSyncValidator, BlockHeaderSyncError};
41
use crate::{
42
    base_node::sync::{
43
        ban::PeerBanManager,
44
        header_sync::HEADER_SYNC_INITIAL_MAX_HEADERS,
45
        hooks::Hooks,
46
        rpc,
47
        BlockchainSyncConfig,
48
        SyncPeer,
49
    },
50
    blocks::{BlockHeader, ChainBlock, ChainHeader},
51
    chain_storage::{async_db::AsyncBlockchainDb, BlockchainBackend, ChainStorageError},
52
    common::{rolling_avg::RollingAverageTime, BanPeriod},
53
    consensus::ConsensusManager,
54
    proof_of_work::randomx_factory::RandomXFactory,
55
    proto::{
56
        base_node::{FindChainSplitRequest, SyncHeadersRequest},
57
        core::BlockHeader as ProtoBlockHeader,
58
    },
59
};
60

61
const LOG_TARGET: &str = "c::bn::header_sync";
62

63
const MAX_LATENCY_INCREASES: usize = 5;
64

65
pub struct HeaderSynchronizer<'a, B> {
66
    config: BlockchainSyncConfig,
67
    db: AsyncBlockchainDb<B>,
68
    header_validator: BlockHeaderSyncValidator<B>,
69
    connectivity: ConnectivityRequester,
70
    sync_peers: &'a mut Vec<SyncPeer>,
71
    hooks: Hooks,
72
    local_cached_metadata: &'a ChainMetadata,
73
    peer_ban_manager: PeerBanManager,
74
}
75

76
impl<'a, B: BlockchainBackend + 'static> HeaderSynchronizer<'a, B> {
77
    pub fn new(
×
78
        config: BlockchainSyncConfig,
×
79
        db: AsyncBlockchainDb<B>,
×
80
        consensus_rules: ConsensusManager,
×
81
        connectivity: ConnectivityRequester,
×
82
        sync_peers: &'a mut Vec<SyncPeer>,
×
83
        randomx_factory: RandomXFactory,
×
84
        local_metadata: &'a ChainMetadata,
×
85
    ) -> Self {
×
86
        let peer_ban_manager = PeerBanManager::new(config.clone(), connectivity.clone());
×
87
        Self {
×
88
            config,
×
89
            header_validator: BlockHeaderSyncValidator::new(db.clone(), consensus_rules, randomx_factory),
×
90
            db,
×
91
            connectivity,
×
92
            sync_peers,
×
93
            hooks: Default::default(),
×
94
            local_cached_metadata: local_metadata,
×
95
            peer_ban_manager,
×
96
        }
×
97
    }
×
98

99
    pub fn on_starting<H>(&mut self, hook: H)
×
100
    where for<'r> H: FnOnce(&SyncPeer) + Send + Sync + 'static {
×
101
        self.hooks.add_on_starting_hook(hook);
×
102
    }
×
103

104
    pub fn on_progress<H>(&mut self, hook: H)
×
105
    where H: Fn(u64, u64, &SyncPeer) + Send + Sync + 'static {
×
106
        self.hooks.add_on_progress_header_hook(hook);
×
107
    }
×
108

109
    pub fn on_rewind<H>(&mut self, hook: H)
×
110
    where H: Fn(Vec<Arc<ChainBlock>>) + Send + Sync + 'static {
×
111
        self.hooks.add_on_rewind_hook(hook);
×
112
    }
×
113

114
    pub async fn synchronize(&mut self) -> Result<(SyncPeer, AttemptSyncResult), BlockHeaderSyncError> {
×
115
        debug!(target: LOG_TARGET, "Starting header sync.",);
×
116

117
        info!(
×
118
            target: LOG_TARGET,
×
119
            "Synchronizing headers ({} candidate peers selected)",
×
120
            self.sync_peers.len()
×
121
        );
122
        let mut max_latency = self.config.initial_max_sync_latency;
×
123
        let mut latency_increases_counter = 0;
×
124
        loop {
125
            match self.try_sync_from_all_peers(max_latency).await {
×
126
                Ok((peer, sync_result)) => break Ok((peer, sync_result)),
×
127
                Err(err @ BlockHeaderSyncError::AllSyncPeersExceedLatency) => {
×
128
                    // If we have few sync peers, throw this out to be retried later
×
129
                    if self.sync_peers.len() < 2 {
×
130
                        return Err(err);
×
131
                    }
×
132
                    max_latency += self.config.max_latency_increase;
×
133
                    latency_increases_counter += 1;
×
134
                    if latency_increases_counter > MAX_LATENCY_INCREASES {
×
135
                        return Err(err);
×
136
                    }
×
137
                },
138
                Err(err) => break Err(err),
×
139
            }
140
        }
141
    }
×
142

143
    #[allow(clippy::too_many_lines)]
144
    pub async fn try_sync_from_all_peers(
×
145
        &mut self,
×
146
        max_latency: Duration,
×
147
    ) -> Result<(SyncPeer, AttemptSyncResult), BlockHeaderSyncError> {
×
148
        let sync_peer_node_ids = self.sync_peers.iter().map(|p| p.node_id()).cloned().collect::<Vec<_>>();
×
149
        info!(
×
150
            target: LOG_TARGET,
×
151
            "Attempting to sync headers ({} sync peers)",
×
152
            sync_peer_node_ids.len()
×
153
        );
154
        let mut latency_counter = 0usize;
×
155
        for node_id in sync_peer_node_ids {
×
156
            match self.connect_and_attempt_sync(&node_id, max_latency).await {
×
157
                Ok((peer, sync_result)) => return Ok((peer, sync_result)),
×
158
                Err(err) => {
×
159
                    let ban_reason = BlockHeaderSyncError::get_ban_reason(&err);
×
160
                    if let Some(reason) = ban_reason {
×
NEW
161
                        warn!(target: LOG_TARGET, "{err}");
×
162
                        let duration = match reason.ban_duration {
×
163
                            BanPeriod::Short => self.config.short_ban_period,
×
164
                            BanPeriod::Long => self.config.ban_period,
×
165
                        };
166
                        self.peer_ban_manager
×
167
                            .ban_peer_if_required(&node_id, reason.reason, duration)
×
168
                            .await;
×
169
                    }
×
170
                    if let BlockHeaderSyncError::MaxLatencyExceeded { .. } = err {
×
171
                        latency_counter += 1;
×
172
                    } else {
×
173
                        self.remove_sync_peer(&node_id);
×
174
                    }
×
175
                },
176
            }
177
        }
178

179
        if self.sync_peers.is_empty() {
×
180
            Err(BlockHeaderSyncError::NoMoreSyncPeers("Header sync failed".to_string()))
×
181
        } else if latency_counter >= self.sync_peers.len() {
×
182
            Err(BlockHeaderSyncError::AllSyncPeersExceedLatency)
×
183
        } else {
184
            Err(BlockHeaderSyncError::SyncFailedAllPeers)
×
185
        }
186
    }
×
187

188
    async fn connect_and_attempt_sync(
×
189
        &mut self,
×
190
        node_id: &NodeId,
×
191
        max_latency: Duration,
×
192
    ) -> Result<(SyncPeer, AttemptSyncResult), BlockHeaderSyncError> {
×
193
        let peer_index = self
×
194
            .get_sync_peer_index(node_id)
×
195
            .ok_or(BlockHeaderSyncError::PeerNotFound)?;
×
NEW
196
        let sync_peer = self.sync_peers.get(peer_index).expect("Already checked");
×
197
        self.hooks.call_on_starting_hook(sync_peer);
×
198

199
        let mut conn = self.dial_sync_peer(node_id).await?;
×
200
        debug!(
×
201
            target: LOG_TARGET,
×
NEW
202
            "Attempting to synchronize headers with `{node_id}`"
×
203
        );
204

205
        let config = RpcClient::builder()
×
206
            .with_deadline(self.config.rpc_deadline)
×
207
            .with_deadline_grace_period(Duration::from_secs(5));
×
208
        let mut client = conn
×
209
            .connect_rpc_using_builder::<rpc::BaseNodeSyncRpcClient>(config)
×
210
            .await?;
×
211

212
        let latency = client
×
213
            .get_last_request_latency()
×
214
            .expect("unreachable panic: last request latency must be set after connect");
×
NEW
215
        self.sync_peers
×
NEW
216
            .get_mut(peer_index)
×
NEW
217
            .ok_or(BlockHeaderSyncError::PeerNotFound)?
×
NEW
218
            .set_latency(latency);
×
219
        if latency > max_latency {
×
220
            return Err(BlockHeaderSyncError::MaxLatencyExceeded {
×
221
                peer: conn.peer_node_id().clone(),
×
222
                latency,
×
223
                max_latency,
×
224
            });
×
225
        }
×
226

×
NEW
227
        debug!(target: LOG_TARGET, "Sync peer latency is {latency:.2?}");
×
NEW
228
        let sync_peer = self
×
NEW
229
            .sync_peers
×
NEW
230
            .get(peer_index)
×
NEW
231
            .ok_or(BlockHeaderSyncError::PeerNotFound)?
×
NEW
232
            .clone();
×
233
        let sync_result = self.attempt_sync(&sync_peer, client, max_latency).await?;
×
234
        Ok((sync_peer, sync_result))
×
235
    }
×
236

237
    async fn dial_sync_peer(&self, node_id: &NodeId) -> Result<PeerConnection, BlockHeaderSyncError> {
×
238
        let timer = Instant::now();
×
NEW
239
        debug!(target: LOG_TARGET, "Dialing {node_id} sync peer");
×
240
        let conn = self.connectivity.dial_peer(node_id.clone()).await?;
×
241
        info!(
×
242
            target: LOG_TARGET,
×
UNCOV
243
            "Successfully dialed sync peer {} in {:.2?}",
×
244
            node_id,
×
245
            timer.elapsed()
×
246
        );
247
        Ok(conn)
×
248
    }
×
249

250
    async fn attempt_sync(
×
251
        &mut self,
×
252
        sync_peer: &SyncPeer,
×
UNCOV
253
        mut client: rpc::BaseNodeSyncRpcClient,
×
254
        max_latency: Duration,
×
255
    ) -> Result<AttemptSyncResult, BlockHeaderSyncError> {
×
UNCOV
256
        let latency = client.get_last_request_latency();
×
257
        debug!(
×
258
            target: LOG_TARGET,
×
259
            "Initiating header sync with peer `{}` (sync latency = {}ms)",
×
260
            sync_peer.node_id(),
×
261
            latency.unwrap_or_default().as_millis()
×
262
        );
263

264
        // Fetch best local data at the beginning of the sync process
265
        let best_block_metadata = self.db.get_chain_metadata().await?;
×
266
        let best_header = self.db.fetch_last_chain_header().await?;
×
267
        let best_block_header = self
×
268
            .db
×
UNCOV
269
            .fetch_chain_header(best_block_metadata.best_block_height())
×
UNCOV
270
            .await?;
×
UNCOV
271
        let best_header_height = best_header.height();
×
272
        let best_block_height = best_block_header.height();
×
273

×
274
        if best_header_height < best_block_height || best_block_height < self.local_cached_metadata.best_block_height()
×
275
        {
276
            return Err(BlockHeaderSyncError::ChainStorageError(
×
277
                ChainStorageError::CorruptedDatabase("Inconsistent block and header data".to_string()),
×
278
            ));
×
279
        }
×
280

281
        // - At this point we may have more (InSyncOrAhead), equal (InSyncOrAhead), or less headers (Lagging) than the
282
        //   peer, but they claimed better POW before we attempted sync.
283
        // - This method will return ban-able errors for certain offenses.
284
        let (header_sync_status, peer_response) = self
×
285
            .determine_sync_status(sync_peer, best_header.clone(), best_block_header.clone(), &mut client)
×
286
            .await?;
×
287

UNCOV
288
        match header_sync_status.clone() {
×
289
            HeaderSyncStatus::InSyncOrAhead => {
UNCOV
290
                debug!(
×
291
                    target: LOG_TARGET,
×
NEW
292
                    "Headers are in sync at height {best_header_height} but tip is {best_block_height}. Proceeding to archival/pruned block sync"
×
293
                );
294

295
                Ok(AttemptSyncResult {
×
296
                    headers_returned: peer_response.peer_headers.len() as u64,
×
297
                    peer_fork_hash_index: peer_response.peer_fork_hash_index,
×
UNCOV
298
                    header_sync_status,
×
UNCOV
299
                })
×
300
            },
301
            HeaderSyncStatus::Lagging(split_info) => {
×
302
                self.hooks.call_on_progress_header_hooks(
×
303
                    split_info
×
304
                        .best_block_header
×
UNCOV
305
                        .height()
×
306
                        .checked_sub(split_info.reorg_steps_back)
×
307
                        .unwrap_or_default(),
×
308
                    sync_peer.claimed_chain_metadata().best_block_height(),
×
309
                    sync_peer,
×
310
                );
×
311
                self.synchronize_headers(sync_peer.clone(), &mut client, *split_info, max_latency)
×
312
                    .await?;
×
313
                Ok(AttemptSyncResult {
×
314
                    headers_returned: peer_response.peer_headers.len() as u64,
×
315
                    peer_fork_hash_index: peer_response.peer_fork_hash_index,
×
316
                    header_sync_status,
×
317
                })
×
318
            },
319
        }
320
    }
×
321

322
    #[allow(clippy::too_many_lines)]
UNCOV
323
    async fn find_chain_split(
×
UNCOV
324
        &mut self,
×
325
        peer_node_id: &NodeId,
×
UNCOV
326
        client: &mut rpc::BaseNodeSyncRpcClient,
×
UNCOV
327
        header_count: u64,
×
328
    ) -> Result<FindChainSplitResult, BlockHeaderSyncError> {
×
329
        const NUM_CHAIN_SPLIT_HEADERS: usize = 500;
330
        // Limit how far back we're willing to go. A peer might just say it does not have a chain split
331
        // and keep us busy going back until the genesis.
332
        // 20 x 500 = max 10,000 block split can be detected
333
        const MAX_CHAIN_SPLIT_ITERS: usize = 20;
334

UNCOV
335
        let mut offset = 0;
×
UNCOV
336
        let mut iter_count = 0;
×
337
        loop {
UNCOV
338
            iter_count += 1;
×
UNCOV
339
            if iter_count > MAX_CHAIN_SPLIT_ITERS {
×
340
                warn!(
×
341
                    target: LOG_TARGET,
×
UNCOV
342
                    "Peer `{}` did not provide a chain split after {} headers requested. Peer will be banned.",
×
343
                    peer_node_id,
×
344
                    NUM_CHAIN_SPLIT_HEADERS * MAX_CHAIN_SPLIT_ITERS,
×
345
                );
346
                return Err(BlockHeaderSyncError::ChainSplitNotFound(peer_node_id.clone()));
×
347
            }
×
348

349
            let block_hashes = self
×
UNCOV
350
                .db
×
351
                .fetch_block_hashes_from_header_tip(NUM_CHAIN_SPLIT_HEADERS, offset)
×
352
                .await?;
×
UNCOV
353
            debug!(
×
354
                target: LOG_TARGET,
×
355
                "Determining if chain splits between {} and {} headers back from the tip (peer: `{}`, {} hashes sent)",
×
356
                offset,
×
357
                offset + NUM_CHAIN_SPLIT_HEADERS,
×
358
                peer_node_id,
×
359
                block_hashes.len()
×
360
            );
361

362
            // No further hashes to send.
363
            if block_hashes.is_empty() {
×
364
                warn!(
×
UNCOV
365
                    target: LOG_TARGET,
×
UNCOV
366
                    "Peer `{}` did not provide a chain split after {} headers requested. Peer will be banned.",
×
UNCOV
367
                    peer_node_id,
×
368
                    NUM_CHAIN_SPLIT_HEADERS * MAX_CHAIN_SPLIT_ITERS,
×
369
                );
370
                return Err(BlockHeaderSyncError::ChainSplitNotFound(peer_node_id.clone()));
×
371
            }
×
372

×
373
            let request = FindChainSplitRequest {
×
UNCOV
374
                block_hashes: block_hashes.clone().iter().map(|v| v.to_vec()).collect(),
×
375
                header_count,
×
376
            };
×
377

378
            let resp = match client.find_chain_split(request).await {
×
379
                Ok(r) => r,
×
380
                Err(RpcError::RequestFailed(err)) if err.as_status_code().is_not_found() => {
×
381
                    // This round we sent less hashes than the max, so the next round will not have any more hashes to
×
UNCOV
382
                    // send. Exit early in this case.
×
383
                    if block_hashes.len() < NUM_CHAIN_SPLIT_HEADERS {
×
384
                        warn!(
×
385
                            target: LOG_TARGET,
×
386
                            "Peer `{}` did not provide a chain split after {} headers requested. Peer will be banned.",
×
387
                            peer_node_id,
×
388
                            NUM_CHAIN_SPLIT_HEADERS * MAX_CHAIN_SPLIT_ITERS,
×
389
                        );
390
                        return Err(BlockHeaderSyncError::ChainSplitNotFound(peer_node_id.clone()));
×
391
                    }
×
392
                    // Chain split not found, let's go further back
×
393
                    offset = NUM_CHAIN_SPLIT_HEADERS * iter_count;
×
UNCOV
394
                    continue;
×
395
                },
396
                Err(err) => {
×
397
                    return Err(err.into());
×
398
                },
399
            };
UNCOV
400
            if resp.headers.len() > HEADER_SYNC_INITIAL_MAX_HEADERS {
×
401
                warn!(
×
402
                    target: LOG_TARGET,
×
UNCOV
403
                    "Peer `{}` sent too many headers {}, only requested {}. Peer will be banned.",
×
UNCOV
404
                    peer_node_id,
×
405
                    resp.headers.len(),
×
406
                    HEADER_SYNC_INITIAL_MAX_HEADERS,
407
                );
408
                return Err(BlockHeaderSyncError::PeerSentTooManyHeaders(resp.headers.len()));
×
409
            }
×
410
            if resp.fork_hash_index >= block_hashes.len() as u64 {
×
UNCOV
411
                warn!(
×
UNCOV
412
                    target: LOG_TARGET,
×
413
                    "Peer `{}` sent hash index {} out of range {}. Peer will be banned.",
×
414
                    peer_node_id,
×
415
                    resp.fork_hash_index,
×
416
                    block_hashes.len(),
×
417
                );
418
                return Err(BlockHeaderSyncError::FoundHashIndexOutOfRange(
×
419
                    block_hashes.len() as u64,
×
420
                    resp.fork_hash_index,
×
421
                ));
×
UNCOV
422
            }
×
423
            #[allow(clippy::cast_possible_truncation)]
×
NEW
424
            if !resp.headers.is_empty() &&
×
NEW
425
                *resp.headers.first().expect("Already checked").prev_hash !=
×
NEW
426
                    *block_hashes
×
NEW
427
                        .get(resp.fork_hash_index as usize)
×
NEW
428
                        .expect("Already checked")
×
429
            {
430
                warn!(
×
431
                    target: LOG_TARGET,
×
432
                    "Peer `{}` sent hash an invalid protocol response, incorrect fork hash index {}. Peer will be banned.",
×
433
                    peer_node_id,
434
                    resp.fork_hash_index,
435
                );
436
                return Err(BlockHeaderSyncError::InvalidProtocolResponse(
×
437
                    "Peer sent incorrect fork hash index".into(),
×
438
                ));
×
UNCOV
439
            }
×
440
            #[allow(clippy::cast_possible_truncation)]
×
NEW
441
            let chain_split_hash = *block_hashes
×
NEW
442
                .get(resp.fork_hash_index as usize)
×
NEW
443
                .expect("Already checked");
×
UNCOV
444

×
UNCOV
445
            return Ok(FindChainSplitResult {
×
UNCOV
446
                reorg_steps_back: resp.fork_hash_index.saturating_add(offset as u64),
×
UNCOV
447
                peer_headers: resp.headers,
×
448
                peer_fork_hash_index: resp.fork_hash_index,
×
449
                chain_split_hash,
×
450
            });
×
451
        }
452
    }
×
453

454
    /// Attempt to determine the point at which the remote and local chain diverge, returning the relevant information
455
    /// of the chain split (see [HeaderSyncStatus]).
456
    ///
457
    /// If the local node is behind the remote chain (i.e. `HeaderSyncStatus::Lagging`), the appropriate
458
    /// `ChainSplitInfo` is returned, the header validator is initialized and the preliminary headers are validated.
459
    async fn determine_sync_status(
×
460
        &mut self,
×
461
        sync_peer: &SyncPeer,
×
462
        best_header: ChainHeader,
×
UNCOV
463
        best_block_header: ChainHeader,
×
464
        client: &mut rpc::BaseNodeSyncRpcClient,
×
UNCOV
465
    ) -> Result<(HeaderSyncStatus, FindChainSplitResult), BlockHeaderSyncError> {
×
466
        // This method will return ban-able errors for certain offenses.
UNCOV
467
        let chain_split_result = self
×
UNCOV
468
            .find_chain_split(sync_peer.node_id(), client, HEADER_SYNC_INITIAL_MAX_HEADERS as u64)
×
UNCOV
469
            .await?;
×
UNCOV
470
        if chain_split_result.reorg_steps_back > 0 {
×
471
            debug!(
×
472
                target: LOG_TARGET,
×
473
                "Found chain split {} blocks back, received {} headers from peer `{}`",
×
474
                chain_split_result.reorg_steps_back,
×
475
                chain_split_result.peer_headers.len(),
×
476
                sync_peer
477
            );
UNCOV
478
        }
×
479

480
        // If the peer returned no new headers, they may still have more blocks than we have, thus have a higher
481
        // accumulated difficulty.
482
        if chain_split_result.peer_headers.is_empty() {
×
483
            // Our POW is less than the peer's POW, as verified before the attempted header sync, therefore, if the
484
            // peer did not supply any headers and we know we are behind based on the peer's claimed metadata, then
485
            // we can ban the peer.
486
            if best_header.height() == best_block_header.height() {
×
487
                warn!(
×
UNCOV
488
                    target: LOG_TARGET,
×
UNCOV
489
                    "Peer `{}` did not provide any headers although they have a better chain and more headers: their \
×
490
                    difficulty: {}, our difficulty: {}. Peer will be banned.",
×
UNCOV
491
                    sync_peer.node_id(),
×
UNCOV
492
                    sync_peer.claimed_chain_metadata().accumulated_difficulty(),
×
UNCOV
493
                    best_block_header.accumulated_data().total_accumulated_difficulty,
×
494
                );
UNCOV
495
                return Err(BlockHeaderSyncError::PeerSentInaccurateChainMetadata {
×
UNCOV
496
                    claimed: sync_peer.claimed_chain_metadata().accumulated_difficulty(),
×
UNCOV
497
                    actual: None,
×
498
                    local: best_block_header.accumulated_data().total_accumulated_difficulty,
×
499
                });
×
500
            }
×
501
            debug!(target: LOG_TARGET, "Peer `{}` sent no headers; headers already in sync with peer.", sync_peer.node_id());
×
502
            return Ok((HeaderSyncStatus::InSyncOrAhead, chain_split_result));
×
503
        }
×
504

505
        let headers = chain_split_result
×
UNCOV
506
            .peer_headers
×
507
            .clone()
×
508
            .into_iter()
×
509
            .map(BlockHeader::try_from)
×
510
            .collect::<Result<Vec<_>, _>>()
×
511
            .map_err(BlockHeaderSyncError::ReceivedInvalidHeader)?;
×
512
        let num_new_headers = headers.len();
×
513
        // Do a cheap check to verify that we do not have these series of headers in the db already - if the 1st one is
×
514
        // not there most probably the rest are not either - the peer could still have returned old headers later on in
×
515
        // the list
×
NEW
516
        if self
×
NEW
517
            .db
×
NEW
518
            .fetch_header_by_block_hash(headers.first().expect("Already checked").hash())
×
NEW
519
            .await?
×
NEW
520
            .is_some()
×
521
        {
522
            return Err(BlockHeaderSyncError::ReceivedInvalidHeader(
×
523
                "Header already in database".to_string(),
×
524
            ));
×
525
        };
×
526

×
527
        self.header_validator
×
528
            .initialize_state(&chain_split_result.chain_split_hash)
×
529
            .await?;
×
530
        for header in headers {
×
531
            debug!(
×
532
                target: LOG_TARGET,
×
533
                "Validating header #{} (Pow: {}) with hash: ({})",
×
534
                header.height,
×
535
                header.pow_algo(),
×
536
                header.hash().to_hex(),
×
537
            );
UNCOV
538
            self.header_validator.validate(header).await?;
×
539
        }
540

541
        debug!(
×
542
            target: LOG_TARGET,
×
543
            "Peer `{}` has submitted {} valid header(s)", sync_peer.node_id(), num_new_headers
×
544
        );
545

546
        let chain_split_info = ChainSplitInfo {
×
547
            best_block_header,
×
548
            reorg_steps_back: chain_split_result.reorg_steps_back,
×
549
            chain_split_hash: chain_split_result.chain_split_hash,
×
550
        };
×
551
        Ok((
×
552
            HeaderSyncStatus::Lagging(Box::new(chain_split_info)),
×
553
            chain_split_result,
×
UNCOV
554
        ))
×
555
    }
×
556

UNCOV
557
    async fn rewind_blockchain(&self, split_hash: HashOutput) -> Result<Vec<Arc<ChainBlock>>, BlockHeaderSyncError> {
×
558
        debug!(
×
559
            target: LOG_TARGET,
×
560
            "Deleting headers that no longer form part of the main chain up until split at {}",
×
UNCOV
561
            split_hash.to_hex()
×
562
        );
563

564
        let blocks = self.db.rewind_to_hash(split_hash).await?;
×
565
        debug!(
×
566
            target: LOG_TARGET,
×
567
            "Rewound {} block(s) in preparation for header sync",
×
568
            blocks.len()
×
569
        );
570
        Ok(blocks)
×
571
    }
×
572

573
    #[allow(clippy::too_many_lines)]
574
    async fn synchronize_headers(
×
575
        &mut self,
×
576
        mut sync_peer: SyncPeer,
×
577
        client: &mut rpc::BaseNodeSyncRpcClient,
×
578
        split_info: ChainSplitInfo,
×
UNCOV
579
        max_latency: Duration,
×
UNCOV
580
    ) -> Result<(), BlockHeaderSyncError> {
×
NEW
581
        info!(target: LOG_TARGET, "Starting header sync from peer {sync_peer}");
×
582
        const COMMIT_EVERY_N_HEADERS: usize = 1000;
583

584
        let mut has_switched_to_new_chain = false;
×
585
        let pending_len = self.header_validator.valid_headers().len();
×
UNCOV
586

×
587
        // Find the hash to start syncing the rest of the headers.
×
588
        // The expectation cannot fail because there has been at least one valid header returned (checked in
×
UNCOV
589
        // determine_sync_status)
×
UNCOV
590
        let (start_header_height, start_header_hash, total_accumulated_difficulty) = self
×
591
            .header_validator
×
592
            .current_valid_chain_tip_header()
×
593
            .map(|h| (h.height(), *h.hash(), h.accumulated_data().total_accumulated_difficulty))
×
594
            .expect("synchronize_headers: expected there to be a valid tip header but it was None");
×
595

×
596
        // If we already have a stronger chain at this point, switch over to it.
×
597
        // just in case we happen to be exactly HEADER_SYNC_INITIAL_MAX_HEADERS headers behind.
×
598
        let has_better_pow = self.pending_chain_has_higher_pow(&split_info.best_block_header);
×
UNCOV
599

×
UNCOV
600
        if has_better_pow {
×
601
            debug!(
×
602
                target: LOG_TARGET,
×
603
                "Remote chain from peer {} has higher PoW. Switching",
×
604
                sync_peer.node_id()
×
605
            );
606
            self.switch_to_pending_chain(&split_info).await?;
×
607
            has_switched_to_new_chain = true;
×
608
        }
×
609

610
        if pending_len < HEADER_SYNC_INITIAL_MAX_HEADERS {
×
611
            // Peer returned less than the max number of requested headers. This indicates that we have all the
612
            // available headers from the peer.
613
            if !has_better_pow {
×
614
                // Because the pow is less or equal than the current chain the peer had to have lied about their pow
615
                debug!(target: LOG_TARGET, "No further headers to download");
×
616
                return Err(BlockHeaderSyncError::PeerSentInaccurateChainMetadata {
×
617
                    claimed: sync_peer.claimed_chain_metadata().accumulated_difficulty(),
×
618
                    actual: Some(total_accumulated_difficulty),
×
619
                    local: split_info
×
620
                        .best_block_header
×
621
                        .accumulated_data()
×
UNCOV
622
                        .total_accumulated_difficulty,
×
623
                });
×
624
            }
×
625
            // The pow is higher, we swapped to the higher chain, we have all the better chain headers, we can move on
×
UNCOV
626
            // to block sync.
×
627
            return Ok(());
×
UNCOV
628
        }
×
UNCOV
629

×
630
        debug!(
×
UNCOV
631
            target: LOG_TARGET,
×
632
            "Download remaining headers starting from header #{} from peer `{}`",
×
633
            start_header_height,
×
634
            sync_peer.node_id()
×
635
        );
636
        let request = SyncHeadersRequest {
×
637
            start_hash: start_header_hash.to_vec(),
×
638
            // To the tip!
×
639
            count: 0,
×
640
        };
×
641

642
        let mut header_stream = client.sync_headers(request).await?;
×
643
        debug!(
×
644
            target: LOG_TARGET,
×
645
            "Reading headers from peer `{}`",
×
646
            sync_peer.node_id()
×
647
        );
648

649
        let mut last_sync_timer = Instant::now();
×
650

×
651
        let mut last_total_accumulated_difficulty = U512::zero();
×
UNCOV
652
        let mut avg_latency = RollingAverageTime::new(20);
×
653
        let mut prev_height: Option<u64> = None;
×
654
        while let Some(header) = header_stream.next().await {
×
655
            let latency = last_sync_timer.elapsed();
×
656
            avg_latency.add_sample(latency);
×
657
            let header = BlockHeader::try_from(header?).map_err(BlockHeaderSyncError::ReceivedInvalidHeader)?;
×
UNCOV
658
            debug!(
×
659
                target: LOG_TARGET,
×
660
                "Validating header #{} (Pow: {}) with hash: ({}). Latency: {:.2?}",
×
661
                header.height,
×
662
                header.pow_algo(),
×
663
                header.hash().to_hex(),
×
664
                latency
665
            );
666
            trace!(
×
667
                target: LOG_TARGET,
×
NEW
668
                "{header}"
×
669
            );
670
            if let Some(prev_header_height) = prev_height {
×
671
                if header.height != prev_header_height.saturating_add(1) {
×
672
                    warn!(
×
673
                        target: LOG_TARGET,
×
674
                        "Received header #{} `{}` does not follow previous header",
×
675
                        header.height,
×
676
                        header.hash().to_hex()
×
677
                    );
678
                    return Err(BlockHeaderSyncError::ReceivedInvalidHeader(
×
679
                        "Header does not follow previous header".to_string(),
×
UNCOV
680
                    ));
×
UNCOV
681
                }
×
682
            }
×
683
            let existing_header = self.db.fetch_header_by_block_hash(header.hash()).await?;
×
684
            if let Some(h) = existing_header {
×
UNCOV
685
                warn!(
×
686
                    target: LOG_TARGET,
×
687
                    "Received header #{} `{}` that we already have.",
×
688
                    h.height,
×
689
                    h.hash().to_hex()
×
690
                );
691
                return Err(BlockHeaderSyncError::ReceivedInvalidHeader(
×
692
                    "Header already in database".to_string(),
×
UNCOV
693
                ));
×
694
            }
×
695
            let current_height = header.height;
×
696
            last_total_accumulated_difficulty = self.header_validator.validate(header).await?;
×
697

698
            if has_switched_to_new_chain {
×
699
                // If we've switched to the new chain, we simply commit every COMMIT_EVERY_N_HEADERS headers
700
                if self.header_validator.valid_headers().len() >= COMMIT_EVERY_N_HEADERS {
×
701
                    self.commit_pending_headers().await?;
×
702
                }
×
703
            } else {
704
                // The remote chain has not (yet) been accepted.
705
                // We check the tip difficulties, switching over to the new chain if a higher accumulated difficulty is
706
                // achieved.
707
                if self.pending_chain_has_higher_pow(&split_info.best_block_header) {
×
708
                    self.switch_to_pending_chain(&split_info).await?;
×
709
                    has_switched_to_new_chain = true;
×
710
                }
×
711
            }
712

UNCOV
713
            sync_peer.set_latency(latency);
×
714
            sync_peer.add_sample(last_sync_timer.elapsed());
×
UNCOV
715
            self.hooks.call_on_progress_header_hooks(
×
716
                current_height,
×
717
                sync_peer.claimed_chain_metadata().best_block_height(),
×
718
                &sync_peer,
×
UNCOV
719
            );
×
UNCOV
720

×
UNCOV
721
            let last_avg_latency = avg_latency.calculate_average_with_min_samples(5);
×
UNCOV
722
            if let Some(avg_latency) = last_avg_latency {
×
723
                if avg_latency > max_latency {
×
724
                    return Err(BlockHeaderSyncError::MaxLatencyExceeded {
×
725
                        peer: sync_peer.node_id().clone(),
×
726
                        latency: avg_latency,
×
UNCOV
727
                        max_latency,
×
UNCOV
728
                    });
×
729
                }
×
730
            }
×
731

732
            last_sync_timer = Instant::now();
×
733
            prev_height = Some(current_height);
×
734
        }
735

736
        if !has_switched_to_new_chain {
×
737
            if sync_peer.claimed_chain_metadata().accumulated_difficulty() <
×
738
                self.header_validator
×
739
                    .current_valid_chain_tip_header()
×
740
                    .map(|h| h.accumulated_data().total_accumulated_difficulty)
×
741
                    .unwrap_or_default()
×
742
            {
743
                // We should only return this error if the peer sent a PoW less than they advertised.
744
                return Err(BlockHeaderSyncError::PeerSentInaccurateChainMetadata {
×
745
                    claimed: sync_peer.claimed_chain_metadata().accumulated_difficulty(),
×
746
                    actual: self
×
UNCOV
747
                        .header_validator
×
748
                        .current_valid_chain_tip_header()
×
749
                        .map(|h| h.accumulated_data().total_accumulated_difficulty),
×
UNCOV
750
                    local: split_info
×
UNCOV
751
                        .best_block_header
×
752
                        .accumulated_data()
×
753
                        .total_accumulated_difficulty,
×
754
                });
×
755
            } else {
756
                warn!(
×
757
                    target: LOG_TARGET,
×
UNCOV
758
                    "Received pow from peer matches claimed, difficulty #{} but local is higher: ({}) and we have not \
×
UNCOV
759
                     swapped. Ignoring",
×
760
                    sync_peer.claimed_chain_metadata().accumulated_difficulty(),
×
761
                    split_info
×
762
                        .best_block_header
×
763
                        .accumulated_data()
×
764
                        .total_accumulated_difficulty
765
                );
766
                return Ok(());
×
767
            }
768
        }
×
769

×
770
        // Commit the last blocks that don't fit into the COMMIT_EVENT_N_HEADERS blocks
×
UNCOV
771
        if !self.header_validator.valid_headers().is_empty() {
×
772
            self.commit_pending_headers().await?;
×
773
        }
×
774

775
        let claimed_total_accumulated_diff = sync_peer.claimed_chain_metadata().accumulated_difficulty();
×
776
        // This rule is strict: if the peer advertised a higher PoW than they were able to provide (without
×
777
        // some other external factor like a disconnect etc), we detect the and ban the peer.
×
778
        if last_total_accumulated_difficulty < claimed_total_accumulated_diff {
×
779
            return Err(BlockHeaderSyncError::PeerSentInaccurateChainMetadata {
×
UNCOV
780
                claimed: claimed_total_accumulated_diff,
×
UNCOV
781
                actual: Some(last_total_accumulated_difficulty),
×
782
                local: split_info
×
UNCOV
783
                    .best_block_header
×
784
                    .accumulated_data()
×
785
                    .total_accumulated_difficulty,
×
786
            });
×
787
        }
×
788

×
789
        Ok(())
×
UNCOV
790
    }
×
791

792
    async fn commit_pending_headers(&mut self) -> Result<ChainHeader, BlockHeaderSyncError> {
×
793
        let chain_headers = self.header_validator.take_valid_headers();
×
794
        let num_headers = chain_headers.len();
×
795
        let start = Instant::now();
×
796

×
797
        let new_tip = chain_headers.last().cloned().unwrap();
×
798
        let mut txn = self.db.write_transaction();
×
799
        chain_headers.into_iter().for_each(|chain_header| {
×
800
            txn.insert_chain_header(chain_header);
×
801
        });
×
802

×
803
        txn.commit().await?;
×
804

805
        debug!(
×
806
            target: LOG_TARGET,
×
UNCOV
807
            "{} header(s) committed (tip = {}) to the blockchain db in {:.2?}",
×
808
            num_headers,
×
809
            new_tip.height(),
×
810
            start.elapsed()
×
811
        );
812

813
        Ok(new_tip)
×
814
    }
×
815

816
    fn pending_chain_has_higher_pow(&self, current_tip: &ChainHeader) -> bool {
×
817
        let chain_headers = self.header_validator.valid_headers();
×
818
        if chain_headers.is_empty() {
×
819
            return false;
×
UNCOV
820
        }
×
821

×
822
        // Check that the remote tip is stronger than the local tip, equal should not have ended up here, so we treat
×
823
        // equal as less
×
824
        let proposed_tip = chain_headers.last().unwrap();
×
825
        self.header_validator.compare_chains(current_tip, proposed_tip).is_lt()
×
826
    }
×
827

UNCOV
828
    async fn switch_to_pending_chain(&mut self, split_info: &ChainSplitInfo) -> Result<(), BlockHeaderSyncError> {
×
829
        // Reorg if required
×
830
        if split_info.reorg_steps_back > 0 {
×
UNCOV
831
            debug!(
×
832
                target: LOG_TARGET,
×
833
                "Reorg: Rewinding the chain by {} block(s) (split hash = {})",
×
834
                split_info.reorg_steps_back,
×
835
                split_info.chain_split_hash.to_hex()
×
836
            );
837
            let blocks = self.rewind_blockchain(split_info.chain_split_hash).await?;
×
838
            if !blocks.is_empty() {
×
839
                self.hooks.call_on_rewind_hooks(blocks);
×
840
            }
×
841
        }
×
842

843
        // Commit the forked chain. At this point
844
        // 1. Headers have been validated
845
        // 2. The forked chain has a higher PoW than the local chain
846
        //
847
        // After this we commit headers every `n` blocks
848
        self.commit_pending_headers().await?;
×
849

850
        Ok(())
×
851
    }
×
852

853
    // Sync peers are also removed from the list of sync peers if the ban duration is longer than the short ban period.
854
    fn remove_sync_peer(&mut self, node_id: &NodeId) {
×
855
        if let Some(pos) = self.sync_peers.iter().position(|p| p.node_id() == node_id) {
×
856
            self.sync_peers.remove(pos);
×
857
        }
×
UNCOV
858
    }
×
859

860
    // Helper function to get the index to the node_id inside of the vec of peers
UNCOV
861
    fn get_sync_peer_index(&mut self, node_id: &NodeId) -> Option<usize> {
×
UNCOV
862
        self.sync_peers.iter().position(|p| p.node_id() == node_id)
×
UNCOV
863
    }
×
864
}
865

866
#[derive(Debug, Clone)]
867
struct FindChainSplitResult {
868
    reorg_steps_back: u64,
869
    peer_headers: Vec<ProtoBlockHeader>,
870
    peer_fork_hash_index: u64,
871
    chain_split_hash: HashOutput,
872
}
873

874
/// Information about the chain split from the remote node.
875
#[derive(Debug, Clone, PartialEq)]
876
pub struct ChainSplitInfo {
877
    /// The best block's header on the local chain.
878
    pub best_block_header: ChainHeader,
879
    /// The number of blocks to reorg back to the fork.
880
    pub reorg_steps_back: u64,
881
    /// The hash of the block at the fork.
882
    pub chain_split_hash: HashOutput,
883
}
884

885
/// The result of an attempt to synchronize headers with a peer.
886
#[derive(Debug, Clone, PartialEq)]
887
pub struct AttemptSyncResult {
888
    /// The number of headers that were returned.
889
    pub headers_returned: u64,
890
    /// The fork hash index of the remote peer.
891
    pub peer_fork_hash_index: u64,
892
    /// The header sync status.
893
    pub header_sync_status: HeaderSyncStatus,
894
}
895

896
#[derive(Debug, Clone, PartialEq)]
897
pub enum HeaderSyncStatus {
898
    /// Local and remote node are in sync or ahead
899
    InSyncOrAhead,
900
    /// Local node is lagging behind remote node
901
    Lagging(Box<ChainSplitInfo>),
902
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc