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

tari-project / tari / 23040501324

13 Mar 2026 07:19AM UTC coverage: 61.695% (-0.04%) from 61.737%
23040501324

push

github

web-flow
chore: create benchmark for console wallet (#7713)

Description
---

70598 of 114431 relevant lines covered (61.69%)

227073.0 hits per line

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

60.14
/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
    sync::Arc,
24
    time::{Duration, Instant},
25
};
26

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

41
pub(crate) use super::{BlockHeaderSyncError, validator::BlockHeaderSyncValidator};
42
use crate::{
43
    base_node::sync::{
44
        BlockchainSyncConfig,
45
        SyncPeer,
46
        ban::PeerBanManager,
47
        header_sync::HEADER_SYNC_INITIAL_MAX_HEADERS,
48
        hooks::Hooks,
49
        rpc,
50
    },
51
    chain_storage::{BlockchainBackend, ChainStorageError, async_db::AsyncBlockchainDb},
52
    common::rolling_avg::RollingAverageTime,
53
    consensus::BaseNodeConsensusManager,
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(
13✔
78
        config: BlockchainSyncConfig,
13✔
79
        db: AsyncBlockchainDb<B>,
13✔
80
        consensus_rules: BaseNodeConsensusManager,
13✔
81
        connectivity: ConnectivityRequester,
13✔
82
        sync_peers: &'a mut Vec<SyncPeer>,
13✔
83
        randomx_factory: RandomXFactory,
13✔
84
        local_metadata: &'a ChainMetadata,
13✔
85
    ) -> Self {
13✔
86
        let peer_ban_manager = PeerBanManager::new(config.clone(), connectivity.clone());
13✔
87
        Self {
13✔
88
            config,
13✔
89
            header_validator: BlockHeaderSyncValidator::new(db.clone(), consensus_rules, randomx_factory),
13✔
90
            db,
13✔
91
            connectivity,
13✔
92
            sync_peers,
13✔
93
            hooks: Default::default(),
13✔
94
            local_cached_metadata: local_metadata,
13✔
95
            peer_ban_manager,
13✔
96
        }
13✔
97
    }
13✔
98

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

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

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

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

117
        info!(
13✔
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;
13✔
123
        let mut latency_increases_counter = 0;
13✔
124
        loop {
125
            match self.try_sync_from_all_peers(max_latency).await {
13✔
126
                Ok((peer, sync_result)) => break Ok((peer, sync_result)),
12✔
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),
1✔
139
            }
140
        }
141
    }
13✔
142

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

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

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

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

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

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

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

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

250
    async fn attempt_sync(
13✔
251
        &mut self,
13✔
252
        sync_peer: &SyncPeer,
13✔
253
        mut client: rpc::BaseNodeSyncRpcClient,
13✔
254
        max_latency: Duration,
13✔
255
    ) -> Result<AttemptSyncResult, BlockHeaderSyncError> {
13✔
256
        let latency = client.get_last_request_latency();
13✔
257
        debug!(
13✔
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?;
13✔
266
        let best_header = self.db.fetch_last_chain_header().await?;
13✔
267
        let best_block_header = self
13✔
268
            .db
13✔
269
            .fetch_chain_header(best_block_metadata.best_block_height())
13✔
270
            .await?;
13✔
271
        let best_header_height = best_header.height();
13✔
272
        let best_block_height = best_block_header.height();
13✔
273

274
        if best_header_height < best_block_height || best_block_height < self.local_cached_metadata.best_block_height()
13✔
275
        {
276
            return Err(BlockHeaderSyncError::ChainStorageError(
×
277
                ChainStorageError::CorruptedDatabase("Inconsistent block and header data".to_string()),
×
278
            ));
×
279
        }
13✔
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
13✔
285
            .determine_sync_status(
13✔
286
                sync_peer,
13✔
287
                best_header.clone(),
13✔
288
                best_block_header.clone(),
13✔
289
                self.config.max_reorg_depth_allowed,
13✔
290
                &mut client,
13✔
291
            )
13✔
292
            .await?;
13✔
293

294
        match header_sync_status.clone() {
12✔
295
            HeaderSyncStatus::InSyncOrAhead => {
296
                debug!(
3✔
297
                    target: LOG_TARGET,
×
298
                    "Headers are in sync at height {best_header_height} but tip is {best_block_height}. Proceeding to archival/pruned block sync"
299
                );
300

301
                Ok(AttemptSyncResult {
3✔
302
                    headers_returned: peer_response.peer_headers.len() as u64,
3✔
303
                    peer_fork_hash_index: peer_response.peer_fork_hash_index,
3✔
304
                    header_sync_status,
3✔
305
                })
3✔
306
            },
307
            HeaderSyncStatus::Lagging(split_info) => {
9✔
308
                self.hooks.call_on_progress_header_hooks(
9✔
309
                    split_info
9✔
310
                        .best_block_header
9✔
311
                        .height()
9✔
312
                        .saturating_sub(split_info.reorg_steps_back),
9✔
313
                    sync_peer.claimed_chain_metadata().best_block_height(),
9✔
314
                    sync_peer,
9✔
315
                );
316
                self.synchronize_headers(sync_peer.clone(), &mut client, *split_info, max_latency)
9✔
317
                    .await?;
9✔
318
                Ok(AttemptSyncResult {
9✔
319
                    headers_returned: peer_response.peer_headers.len() as u64,
9✔
320
                    peer_fork_hash_index: peer_response.peer_fork_hash_index,
9✔
321
                    header_sync_status,
9✔
322
                })
9✔
323
            },
324
        }
325
    }
13✔
326

327
    #[allow(clippy::too_many_lines)]
328
    async fn find_chain_split(
13✔
329
        &mut self,
13✔
330
        peer_node_id: &NodeId,
13✔
331
        max_reorg_depth_allowed: usize,
13✔
332
        client: &mut rpc::BaseNodeSyncRpcClient,
13✔
333
        header_count: u64,
13✔
334
    ) -> Result<FindChainSplitResult, BlockHeaderSyncError> {
13✔
335
        const NUM_CHAIN_SPLIT_HEADERS: usize = 500;
336
        // Limit how far back we're willing to go. A peer might just say it does not have a chain split
337
        // and keep us busy going back until the genesis.
338
        // 20 x 500 = max 10,000 block split can be detected. The 10_000 limit is default, but can be overridden
339
        let max_chain_split_iters = max_reorg_depth_allowed.saturating_div(NUM_CHAIN_SPLIT_HEADERS);
13✔
340

341
        let mut offset = 0;
13✔
342
        let mut iter_count = 0;
13✔
343
        loop {
344
            iter_count += 1;
13✔
345
            if iter_count > max_chain_split_iters {
13✔
346
                warn!(
×
347
                    target: LOG_TARGET,
×
348
                    "Peer `{}` did not provide a chain split after {} headers requested. Peer will be banned.",
349
                    peer_node_id,
350
                    NUM_CHAIN_SPLIT_HEADERS * max_chain_split_iters,
×
351
                );
352
                return Err(BlockHeaderSyncError::ChainSplitNotFound(peer_node_id.clone()));
×
353
            }
13✔
354

355
            let block_hashes = self
13✔
356
                .db
13✔
357
                .fetch_block_hashes_from_header_tip(NUM_CHAIN_SPLIT_HEADERS, offset)
13✔
358
                .await?;
13✔
359
            debug!(
13✔
360
                target: LOG_TARGET,
×
361
                "Determining if chain splits between {} and {} headers back from the tip (peer: `{}`, {} hashes sent)",
362
                offset,
363
                offset + NUM_CHAIN_SPLIT_HEADERS,
×
364
                peer_node_id,
365
                block_hashes.len()
×
366
            );
367

368
            // No further hashes to send.
369
            if block_hashes.is_empty() {
13✔
370
                warn!(
×
371
                    target: LOG_TARGET,
×
372
                    "Peer `{}` did not provide a chain split after {} headers requested. Peer will be banned.",
373
                    peer_node_id,
374
                    NUM_CHAIN_SPLIT_HEADERS * max_chain_split_iters,
×
375
                );
376
                return Err(BlockHeaderSyncError::ChainSplitNotFound(peer_node_id.clone()));
×
377
            }
13✔
378

379
            let request = FindChainSplitRequest {
13✔
380
                block_hashes: block_hashes.clone().iter().map(|v| v.to_vec()).collect(),
56✔
381
                header_count,
13✔
382
            };
383

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

451
            return Ok(FindChainSplitResult {
13✔
452
                reorg_steps_back: resp.fork_hash_index.saturating_add(offset as u64),
13✔
453
                peer_headers: resp.headers,
13✔
454
                peer_fork_hash_index: resp.fork_hash_index,
13✔
455
                chain_split_hash,
13✔
456
            });
13✔
457
        }
458
    }
13✔
459

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

492
        // If the peer returned no new headers, they may still have more blocks than we have, thus have a higher
493
        // accumulated difficulty.
494
        if chain_split_result.peer_headers.is_empty() {
13✔
495
            // Our POW is less than the peer's POW, as verified before the attempted header sync, therefore, if the
496
            // peer did not supply any headers and we know we are behind based on the peer's claimed metadata, then
497
            // we can ban the peer.
498
            if best_header.height() == best_block_header.height() {
4✔
499
                warn!(
1✔
500
                    target: LOG_TARGET,
×
501
                    "Peer `{}` did not provide any headers although they have a better chain and more headers: their \
502
                    difficulty: {}, our difficulty: {}. Peer will be banned.",
503
                    sync_peer.node_id(),
×
504
                    sync_peer.claimed_chain_metadata().accumulated_difficulty(),
×
505
                    best_block_header.accumulated_data().total_accumulated_difficulty,
×
506
                );
507
                return Err(BlockHeaderSyncError::PeerSentInaccurateChainMetadata {
1✔
508
                    claimed: sync_peer.claimed_chain_metadata().accumulated_difficulty(),
1✔
509
                    actual: None,
1✔
510
                    local: best_block_header.accumulated_data().total_accumulated_difficulty,
1✔
511
                });
1✔
512
            }
3✔
513
            debug!(target: LOG_TARGET, "Peer `{}` sent no headers; headers already in sync with peer.", sync_peer.node_id());
3✔
514
            return Ok((HeaderSyncStatus::InSyncOrAhead, chain_split_result));
3✔
515
        }
9✔
516

517
        let headers = chain_split_result
9✔
518
            .peer_headers
9✔
519
            .clone()
9✔
520
            .into_iter()
9✔
521
            .map(BlockHeader::try_from)
9✔
522
            .collect::<Result<Vec<_>, _>>()
9✔
523
            .map_err(BlockHeaderSyncError::ReceivedInvalidHeader)?;
9✔
524
        let num_new_headers = headers.len();
9✔
525
        // Do a cheap check to verify that we do not have these series of headers in the db already - if the 1st one is
526
        // not there most probably the rest are not either - the peer could still have returned old headers later on in
527
        // the list
528
        if self
9✔
529
            .db
9✔
530
            .fetch_header_by_block_hash(headers.first().expect("Already checked").hash())
9✔
531
            .await?
9✔
532
            .is_some()
9✔
533
        {
534
            return Err(BlockHeaderSyncError::ReceivedInvalidHeader(
×
535
                "Header already in database".to_string(),
×
536
            ));
×
537
        };
9✔
538

539
        self.header_validator
9✔
540
            .initialize_state(&chain_split_result.chain_split_hash)
9✔
541
            .await?;
9✔
542
        for header in headers {
32✔
543
            debug!(
32✔
544
                target: LOG_TARGET,
×
545
                "Validating header #{} (Pow: {}) with hash: ({})",
546
                header.height,
547
                header.pow_algo(),
×
548
                header.hash().to_hex(),
×
549
            );
550
            self.header_validator.validate(header).await?;
32✔
551
        }
552

553
        debug!(
9✔
554
            target: LOG_TARGET,
×
555
            "Peer `{}` has submitted {} valid header(s)", sync_peer.node_id(), num_new_headers
×
556
        );
557

558
        let chain_split_info = ChainSplitInfo {
9✔
559
            best_block_header,
9✔
560
            reorg_steps_back: chain_split_result.reorg_steps_back,
9✔
561
            chain_split_hash: chain_split_result.chain_split_hash,
9✔
562
        };
9✔
563
        Ok((
9✔
564
            HeaderSyncStatus::Lagging(Box::new(chain_split_info)),
9✔
565
            chain_split_result,
9✔
566
        ))
9✔
567
    }
13✔
568

569
    async fn rewind_blockchain(&self, split_hash: HashOutput) -> Result<Vec<Arc<ChainBlock>>, BlockHeaderSyncError> {
1✔
570
        debug!(
1✔
571
            target: LOG_TARGET,
×
572
            "Deleting headers that no longer form part of the main chain up until split at {}",
573
            split_hash.to_hex()
×
574
        );
575

576
        let blocks = self.db.rewind_to_hash(split_hash).await?;
1✔
577
        debug!(
1✔
578
            target: LOG_TARGET,
×
579
            "Rewound {} block(s) in preparation for header sync",
580
            blocks.len()
×
581
        );
582
        Ok(blocks)
1✔
583
    }
1✔
584

585
    #[allow(clippy::too_many_lines)]
586
    async fn synchronize_headers(
9✔
587
        &mut self,
9✔
588
        mut sync_peer: SyncPeer,
9✔
589
        client: &mut rpc::BaseNodeSyncRpcClient,
9✔
590
        split_info: ChainSplitInfo,
9✔
591
        max_latency: Duration,
9✔
592
    ) -> Result<(), BlockHeaderSyncError> {
9✔
593
        info!(target: LOG_TARGET, "Starting header sync from peer {sync_peer}");
9✔
594
        const COMMIT_EVERY_N_HEADERS: usize = 1000;
595

596
        let mut has_switched_to_new_chain = false;
9✔
597
        let pending_len = self.header_validator.valid_headers().len();
9✔
598

599
        // Find the hash to start syncing the rest of the headers.
600
        // The expectation cannot fail because there has been at least one valid header returned (checked in
601
        // determine_sync_status)
602
        let (start_header_height, start_header_hash, total_accumulated_difficulty) = self
9✔
603
            .header_validator
9✔
604
            .current_valid_chain_tip_header()
9✔
605
            .map(|h| (h.height(), *h.hash(), h.accumulated_data().total_accumulated_difficulty))
9✔
606
            .expect("synchronize_headers: expected there to be a valid tip header but it was None");
9✔
607

608
        // If we already have a stronger chain at this point, switch over to it.
609
        // just in case we happen to be exactly HEADER_SYNC_INITIAL_MAX_HEADERS headers behind.
610
        let has_better_pow = self.pending_chain_has_higher_pow(&split_info.best_block_header);
9✔
611

612
        if has_better_pow {
9✔
613
            debug!(
9✔
614
                target: LOG_TARGET,
×
615
                "Remote chain from peer {} has higher PoW. Switching",
616
                sync_peer.node_id()
×
617
            );
618
            self.switch_to_pending_chain(&split_info).await?;
9✔
619
            has_switched_to_new_chain = true;
9✔
620
        }
×
621

622
        if pending_len < HEADER_SYNC_INITIAL_MAX_HEADERS {
9✔
623
            // Peer returned less than the max number of requested headers. This indicates that we have all the
624
            // available headers from the peer.
625
            if !has_better_pow {
9✔
626
                // Because the pow is less or equal than the current chain the peer had to have lied about their pow
627
                debug!(target: LOG_TARGET, "No further headers to download");
×
628
                return Err(BlockHeaderSyncError::PeerSentInaccurateChainMetadata {
×
629
                    claimed: sync_peer.claimed_chain_metadata().accumulated_difficulty(),
×
630
                    actual: Some(total_accumulated_difficulty),
×
631
                    local: split_info
×
632
                        .best_block_header
×
633
                        .accumulated_data()
×
634
                        .total_accumulated_difficulty,
×
635
                });
×
636
            }
9✔
637
            // The pow is higher, we swapped to the higher chain, we have all the better chain headers, we can move on
638
            // to block sync.
639
            return Ok(());
9✔
640
        }
×
641

642
        debug!(
×
643
            target: LOG_TARGET,
×
644
            "Download remaining headers starting from header #{} from peer `{}`",
645
            start_header_height,
646
            sync_peer.node_id()
×
647
        );
648
        let request = SyncHeadersRequest {
×
649
            start_hash: start_header_hash.to_vec(),
×
650
            // To the tip!
×
651
            count: 0,
×
652
        };
×
653

654
        let mut header_stream = client.sync_headers(request).await?;
×
655
        debug!(
×
656
            target: LOG_TARGET,
×
657
            "Reading headers from peer `{}`",
658
            sync_peer.node_id()
×
659
        );
660

661
        let mut last_sync_timer = Instant::now();
×
662

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

710
            if has_switched_to_new_chain {
×
711
                // If we've switched to the new chain, we simply commit every COMMIT_EVERY_N_HEADERS headers
712
                if self.header_validator.valid_headers().len() >= COMMIT_EVERY_N_HEADERS {
×
713
                    self.commit_pending_headers().await?;
×
714
                }
×
715
            } else {
716
                // The remote chain has not (yet) been accepted.
717
                // We check the tip difficulties, switching over to the new chain if a higher accumulated difficulty is
718
                // achieved.
719
                if self.pending_chain_has_higher_pow(&split_info.best_block_header) {
×
720
                    self.switch_to_pending_chain(&split_info).await?;
×
721
                    has_switched_to_new_chain = true;
×
722
                }
×
723
            }
724

725
            sync_peer.set_latency(latency);
×
726
            sync_peer.add_sample(last_sync_timer.elapsed());
×
727
            self.hooks.call_on_progress_header_hooks(
×
728
                current_height,
×
729
                sync_peer.claimed_chain_metadata().best_block_height(),
×
730
                &sync_peer,
×
731
            );
732

733
            let last_avg_latency = avg_latency.calculate_average_with_min_samples(5);
×
734
            if let Some(avg_latency) = last_avg_latency &&
×
735
                avg_latency > max_latency
×
736
            {
737
                return Err(BlockHeaderSyncError::MaxLatencyExceeded {
×
738
                    peer: sync_peer.node_id().clone(),
×
739
                    latency: avg_latency,
×
740
                    max_latency,
×
741
                });
×
742
            }
×
743

744
            last_sync_timer = Instant::now();
×
745
            prev_height = Some(current_height);
×
746
        }
747

748
        let claimed_total_accumulated_diff = sync_peer.claimed_chain_metadata().accumulated_difficulty();
×
749
        if !has_switched_to_new_chain {
×
750
            let best_local_before_sync = split_info
×
751
                .best_block_header
×
752
                .accumulated_data()
×
753
                .total_accumulated_difficulty;
×
754
            match self
×
755
                .header_validator
×
756
                .current_valid_chain_tip_header()
×
757
                .map(|h| h.accumulated_data().total_accumulated_difficulty)
×
758
            {
759
                Some(validated_total_accumulated_diff) => {
×
760
                    if claimed_total_accumulated_diff > validated_total_accumulated_diff {
×
761
                        // Over-claim: peer advertised more PoW than their headers actually provide.
762
                        return Err(BlockHeaderSyncError::PeerSentInaccurateChainMetadata {
×
763
                            claimed: claimed_total_accumulated_diff,
×
764
                            actual: Some(validated_total_accumulated_diff),
×
765
                            local: best_local_before_sync,
×
766
                        });
×
767
                    } else if self.pending_chain_has_higher_pow(&split_info.best_block_header) {
×
768
                        self.switch_to_pending_chain(&split_info).await?;
×
769
                        has_switched_to_new_chain = true;
×
770
                        info!(
×
771
                            target: LOG_TARGET,
×
772
                            "Received PoW from peer exceeds local tip. Before sync: {}, received: {}. Committed.",
773
                            best_local_before_sync,
774
                            validated_total_accumulated_diff,
775
                        );
776
                    } else {
777
                        // We have a stronger chain, so we do not commit the headers.
778
                        debug!(
×
779
                            target: LOG_TARGET,
×
780
                            "Not committing headers as we have a stronger chain, ours: {} theirs: {}",
781
                            best_local_before_sync,
782
                            validated_total_accumulated_diff,
783
                        );
784
                    };
785
                },
786
                None => {
787
                    // No validated headers at this stage, but there should have been.
788
                    return Err(BlockHeaderSyncError::PeerSentInaccurateChainMetadata {
×
789
                        claimed: claimed_total_accumulated_diff,
×
790
                        actual: None,
×
791
                        local: best_local_before_sync,
×
792
                    });
×
793
                },
794
            }
795
        }
×
796

797
        // Commit the last blocks only if we have switched to the new chain.
798
        if has_switched_to_new_chain && !self.header_validator.valid_headers().is_empty() {
×
799
            self.commit_pending_headers().await?;
×
800
        }
×
801

802
        // This rule is strict: if the peer advertised a higher PoW than they were able to provide (without
803
        // some other external factor like a disconnect etc), we detect the and ban the peer.
804
        if last_total_accumulated_difficulty < claimed_total_accumulated_diff {
×
805
            return Err(BlockHeaderSyncError::PeerSentInaccurateChainMetadata {
×
806
                claimed: claimed_total_accumulated_diff,
×
807
                actual: Some(last_total_accumulated_difficulty),
×
808
                local: split_info
×
809
                    .best_block_header
×
810
                    .accumulated_data()
×
811
                    .total_accumulated_difficulty,
×
812
            });
×
813
        }
×
814

815
        Ok(())
×
816
    }
9✔
817

818
    async fn commit_pending_headers(&mut self) -> Result<ChainHeader, BlockHeaderSyncError> {
9✔
819
        let chain_headers = self.header_validator.take_valid_headers();
9✔
820
        let num_headers = chain_headers.len();
9✔
821
        let start = Instant::now();
9✔
822

823
        let new_tip = chain_headers.last().cloned().unwrap();
9✔
824
        let mut txn = self.db.write_transaction();
9✔
825
        chain_headers.into_iter().for_each(|chain_header| {
32✔
826
            txn.insert_chain_header(chain_header);
32✔
827
        });
32✔
828

829
        txn.commit().await?;
9✔
830

831
        debug!(
9✔
832
            target: LOG_TARGET,
×
833
            "{} header(s) committed (tip = {}) to the blockchain db in {:.2?}",
834
            num_headers,
835
            new_tip.height(),
×
836
            start.elapsed()
×
837
        );
838

839
        Ok(new_tip)
9✔
840
    }
9✔
841

842
    fn pending_chain_has_higher_pow(&self, current_tip: &ChainHeader) -> bool {
9✔
843
        let chain_headers = self.header_validator.valid_headers();
9✔
844
        if chain_headers.is_empty() {
9✔
845
            return false;
×
846
        }
9✔
847

848
        // Check that the remote tip is stronger than the local tip, equal should not have ended up here, so we treat
849
        // equal as less
850
        let proposed_tip = chain_headers.last().unwrap();
9✔
851
        self.header_validator.compare_chains(current_tip, proposed_tip).is_lt()
9✔
852
    }
9✔
853

854
    async fn switch_to_pending_chain(&mut self, split_info: &ChainSplitInfo) -> Result<(), BlockHeaderSyncError> {
9✔
855
        // Reorg if required
856
        if split_info.reorg_steps_back > 0 {
9✔
857
            debug!(
1✔
858
                target: LOG_TARGET,
×
859
                "Reorg: Rewinding the chain by {} block(s) (split hash = {})",
860
                split_info.reorg_steps_back,
861
                split_info.chain_split_hash.to_hex()
×
862
            );
863
            let blocks = self.rewind_blockchain(split_info.chain_split_hash).await?;
1✔
864
            if !blocks.is_empty() {
1✔
865
                self.hooks.call_on_rewind_hooks(blocks);
1✔
866
            }
1✔
867
        }
8✔
868

869
        // Commit the forked chain. At this point
870
        // 1. Headers have been validated
871
        // 2. The forked chain has a higher PoW than the local chain
872
        //
873
        // After this we commit headers every `n` blocks
874
        self.commit_pending_headers().await?;
9✔
875

876
        Ok(())
9✔
877
    }
9✔
878

879
    // Sync peers are also removed from the list of sync peers if the ban duration is longer than the short ban period.
880
    fn remove_sync_peer(&mut self, node_id: &NodeId) {
1✔
881
        if let Some(pos) = self.sync_peers.iter().position(|p| p.node_id() == node_id) {
1✔
882
            self.sync_peers.remove(pos);
1✔
883
        }
1✔
884
    }
1✔
885

886
    // Helper function to get the index to the node_id inside of the vec of peers
887
    fn get_sync_peer_index(&mut self, node_id: &NodeId) -> Option<usize> {
13✔
888
        self.sync_peers.iter().position(|p| p.node_id() == node_id)
13✔
889
    }
13✔
890
}
891

892
#[derive(Debug, Clone)]
893
struct FindChainSplitResult {
894
    reorg_steps_back: u64,
895
    peer_headers: Vec<ProtoBlockHeader>,
896
    peer_fork_hash_index: u64,
897
    chain_split_hash: HashOutput,
898
}
899

900
/// Information about the chain split from the remote node.
901
#[derive(Debug, Clone, PartialEq)]
902
pub struct ChainSplitInfo {
903
    /// The best block's header on the local chain.
904
    pub best_block_header: ChainHeader,
905
    /// The number of blocks to reorg back to the fork.
906
    pub reorg_steps_back: u64,
907
    /// The hash of the block at the fork.
908
    pub chain_split_hash: HashOutput,
909
}
910

911
/// The result of an attempt to synchronize headers with a peer.
912
#[derive(Debug, Clone, PartialEq)]
913
pub struct AttemptSyncResult {
914
    /// The number of headers that were returned.
915
    pub headers_returned: u64,
916
    /// The fork hash index of the remote peer.
917
    pub peer_fork_hash_index: u64,
918
    /// The header sync status.
919
    pub header_sync_status: HeaderSyncStatus,
920
}
921

922
#[derive(Debug, Clone, PartialEq)]
923
pub enum HeaderSyncStatus {
924
    /// Local and remote node are in sync or ahead
925
    InSyncOrAhead,
926
    /// Local node is lagging behind remote node
927
    Lagging(Box<ChainSplitInfo>),
928
}
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