darkfid/proto/
protocol_sync.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
/* This file is part of DarkFi (https://dark.fi)
 *
 * Copyright (C) 2020-2024 Dyne.org foundation
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

use std::sync::Arc;

use async_trait::async_trait;
use log::{debug, error};

use darkfi::{
    blockchain::{BlockInfo, Header, HeaderHash},
    impl_p2p_message,
    net::{
        protocol::protocol_generic::{
            ProtocolGenericAction, ProtocolGenericHandler, ProtocolGenericHandlerPtr,
        },
        session::SESSION_DEFAULT,
        Message, P2pPtr,
    },
    system::ExecutorPtr,
    validator::{consensus::Proposal, ValidatorPtr},
    Error, Result,
};
use darkfi_serial::{SerialDecodable, SerialEncodable};

// Constant defining how many blocks we send during syncing.
pub const BATCH: usize = 20;

/// Structure represening a request to ask a node for their current
/// canonical(confirmed) tip block hash, if they are synced. We also
/// include our own tip, so they can verify we follow the same sequence.
#[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
pub struct TipRequest {
    /// Canonical(confirmed) tip block hash
    pub tip: HeaderHash,
}

impl_p2p_message!(TipRequest, "tiprequest");

/// Structure representing the response to `TipRequest`,
/// containing a boolean flag to indicate if we are synced,
/// and our canonical(confirmed) tip block height and hash.
#[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
pub struct TipResponse {
    /// Flag indicating the node is synced
    pub synced: bool,
    /// Canonical(confirmed) tip block height
    pub height: Option<u32>,
    /// Canonical(confirmed) tip block hash
    pub hash: Option<HeaderHash>,
}

impl_p2p_message!(TipResponse, "tipresponse");

/// Structure represening a request to ask a node for up to `BATCH` headers before
/// the provided header height.
#[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
pub struct HeaderSyncRequest {
    /// Header height
    pub height: u32,
}

impl_p2p_message!(HeaderSyncRequest, "headersyncrequest");

/// Structure representing the response to `HeaderSyncRequest`,
/// containing up to `BATCH` headers before the requested block height.
#[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
pub struct HeaderSyncResponse {
    /// Response headers
    pub headers: Vec<Header>,
}

impl_p2p_message!(HeaderSyncResponse, "headersyncresponse");

/// Structure represening a request to ask a node for up to`BATCH` blocks
/// of provided headers.
#[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
pub struct SyncRequest {
    /// Header hashes
    pub headers: Vec<HeaderHash>,
}

impl_p2p_message!(SyncRequest, "syncrequest");

/// Structure representing the response to `SyncRequest`,
/// containing up to `BATCH` blocks after the requested block height.
#[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
pub struct SyncResponse {
    /// Response blocks
    pub blocks: Vec<BlockInfo>,
}

impl_p2p_message!(SyncResponse, "syncresponse");

/// Structure represening a request to ask a node a fork sequence.
/// If we include a specific fork tip, they have to return its sequence,
/// otherwise they respond with their best fork sequence.
/// We also include our own canonical(confirmed) tip, so they can verify
/// we follow the same sequence.
#[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
pub struct ForkSyncRequest {
    /// Canonical(confirmed) tip block hash
    pub tip: HeaderHash,
    /// Optional fork tip block hash
    pub fork_tip: Option<HeaderHash>,
}

impl_p2p_message!(ForkSyncRequest, "forksyncrequest");

/// Structure representing the response to `ForkSyncRequest`,
/// containing the requested fork sequence.
#[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
pub struct ForkSyncResponse {
    /// Response fork proposals
    pub proposals: Vec<Proposal>,
}

impl_p2p_message!(ForkSyncResponse, "forksyncresponse");

/// Structure represening a request to ask a node a fork header for the
/// requested height. The fork is identified by the provided header hash.
#[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
pub struct ForkHeaderHashRequest {
    /// Header height
    pub height: u32,
    /// Block header hash to identify the fork
    pub fork_header: HeaderHash,
}

impl_p2p_message!(ForkHeaderHashRequest, "forkheaderhashrequest");

/// Structure representing the response to `ForkHeaderHashRequest`,
/// containing the requested fork header hash, if it was found.
#[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
pub struct ForkHeaderHashResponse {
    /// Response fork block header hash
    pub fork_header: Option<HeaderHash>,
}

impl_p2p_message!(ForkHeaderHashResponse, "forkheaderhashresponse");

/// Structure represening a request to ask a node for up to `BATCH`
/// fork headers for provided header hashes.  The fork is identified
/// by the provided header hash.
#[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
pub struct ForkHeadersRequest {
    /// Header hashes
    pub headers: Vec<HeaderHash>,
    /// Block header hash to identify the fork
    pub fork_header: HeaderHash,
}

impl_p2p_message!(ForkHeadersRequest, "forkheadersrequest");

/// Structure representing the response to `ForkHeadersRequest`,
/// containing up to `BATCH` fork headers.
#[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
pub struct ForkHeadersResponse {
    /// Response headers
    pub headers: Vec<Header>,
}

impl_p2p_message!(ForkHeadersResponse, "forkheadersresponse");

/// Structure represening a request to ask a node for up to `BATCH`
/// fork proposals for provided header hashes.  The fork is identified
/// by the provided header hash.
#[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
pub struct ForkProposalsRequest {
    /// Header hashes
    pub headers: Vec<HeaderHash>,
    /// Block header hash to identify the fork
    pub fork_header: HeaderHash,
}

impl_p2p_message!(ForkProposalsRequest, "forkproposalsrequest");

/// Structure representing the response to `ForkProposalsRequest`,
/// containing up to `BATCH` fork headers.
#[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
pub struct ForkProposalsResponse {
    /// Response proposals
    pub proposals: Vec<Proposal>,
}

impl_p2p_message!(ForkProposalsResponse, "forkproposalsresponse");

/// Atomic pointer to the `ProtocolSync` handler.
pub type ProtocolSyncHandlerPtr = Arc<ProtocolSyncHandler>;

/// Handler managing all `ProtocolSync` messages, over generic P2P protocols.
pub struct ProtocolSyncHandler {
    /// The generic handler for `TipRequest` messages.
    tip_handler: ProtocolGenericHandlerPtr<TipRequest, TipResponse>,
    /// The generic handler for `HeaderSyncRequest` messages.
    header_handler: ProtocolGenericHandlerPtr<HeaderSyncRequest, HeaderSyncResponse>,
    /// The generic handler for `SyncRequest` messages.
    sync_handler: ProtocolGenericHandlerPtr<SyncRequest, SyncResponse>,
    /// The generic handler for `ForkSyncRequest` messages.
    fork_sync_handler: ProtocolGenericHandlerPtr<ForkSyncRequest, ForkSyncResponse>,
    /// The generic handler for `ForkHeaderHashRequest` messages.
    fork_header_hash_handler:
        ProtocolGenericHandlerPtr<ForkHeaderHashRequest, ForkHeaderHashResponse>,
    /// The generic handler for `ForkHeadersRequest` messages.
    fork_headers_handler: ProtocolGenericHandlerPtr<ForkHeadersRequest, ForkHeadersResponse>,
    /// The generic handler for `ForkProposalsRequest` messages.
    fork_proposals_handler: ProtocolGenericHandlerPtr<ForkProposalsRequest, ForkProposalsResponse>,
}

impl ProtocolSyncHandler {
    /// Initialize the generic prototocol handlers for all `ProtocolSync` messages
    /// and register them to the provided P2P network, using the default session flag.
    pub async fn init(p2p: &P2pPtr) -> ProtocolSyncHandlerPtr {
        debug!(
            target: "darkfid::proto::protocol_sync::init",
            "Adding all sync protocols to the protocol registry"
        );

        let tip_handler =
            ProtocolGenericHandler::new(p2p, "ProtocolSyncTip", SESSION_DEFAULT).await;
        let header_handler =
            ProtocolGenericHandler::new(p2p, "ProtocolSyncHeader", SESSION_DEFAULT).await;
        let sync_handler = ProtocolGenericHandler::new(p2p, "ProtocolSync", SESSION_DEFAULT).await;
        let fork_sync_handler =
            ProtocolGenericHandler::new(p2p, "ProtocolSyncFork", SESSION_DEFAULT).await;
        let fork_header_hash_handler =
            ProtocolGenericHandler::new(p2p, "ProtocolSyncForkHeaderHash", SESSION_DEFAULT).await;
        let fork_headers_handler =
            ProtocolGenericHandler::new(p2p, "ProtocolSyncForkHeaders", SESSION_DEFAULT).await;
        let fork_proposals_handler =
            ProtocolGenericHandler::new(p2p, "ProtocolSyncForkProposals", SESSION_DEFAULT).await;

        Arc::new(Self {
            tip_handler,
            header_handler,
            sync_handler,
            fork_sync_handler,
            fork_header_hash_handler,
            fork_headers_handler,
            fork_proposals_handler,
        })
    }

    /// Start all `ProtocolSync` background tasks.
    pub async fn start(&self, executor: &ExecutorPtr, validator: &ValidatorPtr) -> Result<()> {
        debug!(
            target: "darkfid::proto::protocol_sync::start",
            "Starting sync protocols handlers tasks..."
        );

        self.tip_handler.task.clone().start(
            handle_receive_tip_request(self.tip_handler.clone(), validator.clone()),
            |res| async move {
                match res {
                    Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
                    Err(e) => error!(target: "darkfid::proto::protocol_sync::start", "Failed starting ProtocolSyncTip handler task: {e}"),
                }
            },
            Error::DetachedTaskStopped,
            executor.clone(),
        );

        self.header_handler.task.clone().start(
            handle_receive_header_request(self.header_handler.clone(), validator.clone()),
            |res| async move {
                match res {
                    Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
                    Err(e) => error!(target: "darkfid::proto::protocol_sync::start", "Failed starting ProtocolSyncHeader handler task: {e}"),
                }
            },
            Error::DetachedTaskStopped,
            executor.clone(),
        );

        self.sync_handler.task.clone().start(
            handle_receive_request(self.sync_handler.clone(), validator.clone()),
            |res| async move {
                match res {
                    Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
                    Err(e) => error!(target: "darkfid::proto::protocol_sync::start", "Failed starting ProtocolSync handler task: {e}"),
                }
            },
            Error::DetachedTaskStopped,
            executor.clone(),
        );

        self.fork_sync_handler.task.clone().start(
            handle_receive_fork_request(self.fork_sync_handler.clone(), validator.clone()),
            |res| async move {
                match res {
                    Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
                    Err(e) => error!(target: "darkfid::proto::protocol_sync::start", "Failed starting ProtocolSyncFork handler task: {e}"),
                }
            },
            Error::DetachedTaskStopped,
            executor.clone(),
        );

        self.fork_header_hash_handler.task.clone().start(
            handle_receive_fork_header_hash_request(self.fork_header_hash_handler.clone(), validator.clone()),
            |res| async move {
                match res {
                    Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
                    Err(e) => error!(target: "darkfid::proto::protocol_sync::start", "Failed starting ProtocolSyncForkHeaderHash handler task: {e}"),
                }
            },
            Error::DetachedTaskStopped,
            executor.clone(),
        );

        self.fork_headers_handler.task.clone().start(
            handle_receive_fork_headers_request(self.fork_headers_handler.clone(), validator.clone()),
            |res| async move {
                match res {
                    Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
                    Err(e) => error!(target: "darkfid::proto::protocol_sync::start", "Failed starting ProtocolSyncForkHeaders handler task: {e}"),
                }
            },
            Error::DetachedTaskStopped,
            executor.clone(),
        );

        self.fork_proposals_handler.task.clone().start(
            handle_receive_fork_proposals_request(self.fork_proposals_handler.clone(), validator.clone()),
            |res| async move {
                match res {
                    Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
                    Err(e) => error!(target: "darkfid::proto::protocol_sync::start", "Failed starting ProtocolSyncForkProposals handler task: {e}"),
                }
            },
            Error::DetachedTaskStopped,
            executor.clone(),
        );

        debug!(
            target: "darkfid::proto::protocol_sync::start",
            "Sync protocols handlers tasks started!"
        );

        Ok(())
    }

    /// Stop all `ProtocolSync` background tasks.
    pub async fn stop(&self) {
        debug!(target: "darkfid::proto::protocol_sync::stop", "Terminating sync protocols handlers tasks...");
        self.tip_handler.task.stop().await;
        self.header_handler.task.stop().await;
        self.sync_handler.task.stop().await;
        self.fork_sync_handler.task.stop().await;
        self.fork_header_hash_handler.task.stop().await;
        self.fork_headers_handler.task.stop().await;
        self.fork_proposals_handler.task.stop().await;
        debug!(target: "darkfid::proto::protocol_sync::stop", "Sync protocols handlers tasks terminated!");
    }
}

/// Background handler function for ProtocolSyncTip.
async fn handle_receive_tip_request(
    handler: ProtocolGenericHandlerPtr<TipRequest, TipResponse>,
    validator: ValidatorPtr,
) -> Result<()> {
    debug!(target: "darkfid::proto::protocol_sync::handle_receive_tip_request", "START");
    loop {
        // Wait for a new tip request message
        let (channel, request) = match handler.receiver.recv().await {
            Ok(r) => r,
            Err(e) => {
                debug!(
                    target: "darkfid::proto::protocol_sync::handle_receive_tip_request",
                    "recv fail: {e}"
                );
                continue
            }
        };

        debug!(target: "darkfid::proto::protocol_sync::handle_receive_tip_request", "Received request: {request:?}");

        // Check if node has finished syncing its blockchain
        if !*validator.synced.read().await {
            debug!(
                target: "darkfid::proto::protocol_sync::handle_receive_tip_request",
                "Node still syncing blockchain"
            );
            handler
                .send_action(
                    channel,
                    ProtocolGenericAction::Response(TipResponse {
                        synced: false,
                        height: None,
                        hash: None,
                    }),
                )
                .await;
            continue
        }

        // Check we follow the same sequence
        match validator.blockchain.blocks.contains(&request.tip) {
            Ok(contains) => {
                if !contains {
                    debug!(
                        target: "darkfid::proto::protocol_sync::handle_receive_tip_request",
                        "Node doesn't follow request sequence"
                    );
                    handler.send_action(channel, ProtocolGenericAction::Skip).await;
                    continue
                }
            }
            Err(e) => {
                error!(
                    target: "darkfid::proto::protocol_sync::handle_receive_tip_request",
                    "block_store.contains fail: {e}"
                );
                handler.send_action(channel, ProtocolGenericAction::Skip).await;
                continue
            }
        }

        // Grab our current tip and return it
        let tip = match validator.blockchain.last() {
            Ok(v) => v,
            Err(e) => {
                error!(
                    target: "darkfid::proto::protocol_sync::handle_receive_tip_request",
                    "blockchain.last fail: {e}"
                );
                handler.send_action(channel, ProtocolGenericAction::Skip).await;
                continue
            }
        };

        // Send response
        handler
            .send_action(
                channel,
                ProtocolGenericAction::Response(TipResponse {
                    synced: true,
                    height: Some(tip.0),
                    hash: Some(tip.1),
                }),
            )
            .await;
    }
}

/// Background handler function for ProtocolSyncHeader.
async fn handle_receive_header_request(
    handler: ProtocolGenericHandlerPtr<HeaderSyncRequest, HeaderSyncResponse>,
    validator: ValidatorPtr,
) -> Result<()> {
    debug!(target: "darkfid::proto::protocol_sync::handle_receive_header_request", "START");
    loop {
        // Wait for a new header request message
        let (channel, request) = match handler.receiver.recv().await {
            Ok(r) => r,
            Err(e) => {
                debug!(
                    target: "darkfid::proto::protocol_sync::handle_receive_header_request",
                    "recv fail: {e}"
                );
                continue
            }
        };

        // Check if node has finished syncing its blockchain
        if !*validator.synced.read().await {
            debug!(
                target: "darkfid::proto::protocol_sync::handle_receive_header_request",
                "Node still syncing blockchain, skipping..."
            );
            handler.send_action(channel, ProtocolGenericAction::Skip).await;
            continue
        }

        debug!(target: "darkfid::proto::protocol_sync::handle_receive_header_request", "Received request: {request:?}");

        // Grab the corresponding headers
        let headers = match validator.blockchain.get_headers_before(request.height, BATCH) {
            Ok(v) => v,
            Err(e) => {
                error!(
                    target: "darkfid::proto::protocol_sync::handle_receive_header_request",
                    "get_headers_before fail: {}",
                    e
                );
                handler.send_action(channel, ProtocolGenericAction::Skip).await;
                continue
            }
        };

        // Send response
        handler
            .send_action(channel, ProtocolGenericAction::Response(HeaderSyncResponse { headers }))
            .await;
    }
}

/// Background handler function for ProtocolSync.
async fn handle_receive_request(
    handler: ProtocolGenericHandlerPtr<SyncRequest, SyncResponse>,
    validator: ValidatorPtr,
) -> Result<()> {
    debug!(target: "darkfid::proto::protocol_sync::handle_receive_request", "START");
    loop {
        // Wait for a new sync request message
        let (channel, request) = match handler.receiver.recv().await {
            Ok(r) => r,
            Err(e) => {
                debug!(
                    target: "darkfid::proto::protocol_sync::handle_receive_request",
                    "recv fail: {e}"
                );
                continue
            }
        };

        // Check if node has finished syncing its blockchain
        if !*validator.synced.read().await {
            debug!(
                target: "darkfid::proto::protocol_sync::handle_receive_request",
                "Node still syncing blockchain, skipping..."
            );
            handler.send_action(channel, ProtocolGenericAction::Skip).await;
            continue
        }

        // Check if request exists the configured limit
        if request.headers.len() > BATCH {
            debug!(
                target: "darkfid::proto::protocol_sync::handle_receive_request",
                "Node requested more blocks than allowed."
            );
            handler.send_action(channel, ProtocolGenericAction::Skip).await;
            continue
        }

        debug!(target: "darkfid::proto::protocol_sync::handle_receive_request", "Received request: {request:?}");

        // Grab the corresponding blocks
        let blocks = match validator.blockchain.get_blocks_by_hash(&request.headers) {
            Ok(v) => v,
            Err(e) => {
                error!(
                    target: "darkfid::proto::protocol_sync::handle_receive_request",
                    "get_blocks_after fail: {}",
                    e
                );
                handler.send_action(channel, ProtocolGenericAction::Skip).await;
                continue
            }
        };

        // Send response
        handler
            .send_action(channel, ProtocolGenericAction::Response(SyncResponse { blocks }))
            .await;
    }
}

/// Background handler function for ProtocolSyncFork.
async fn handle_receive_fork_request(
    handler: ProtocolGenericHandlerPtr<ForkSyncRequest, ForkSyncResponse>,
    validator: ValidatorPtr,
) -> Result<()> {
    debug!(target: "darkfid::proto::protocol_sync::handle_receive_fork_request", "START");
    loop {
        // Wait for a new fork sync request message
        let (channel, request) = match handler.receiver.recv().await {
            Ok(r) => r,
            Err(e) => {
                debug!(
                    target: "darkfid::proto::protocol_sync::handle_receive_fork_request",
                    "recv fail: {e}"
                );
                continue
            }
        };

        // Check if node has finished syncing its blockchain
        if !*validator.synced.read().await {
            debug!(
                target: "darkfid::proto::protocol_sync::handle_receive_fork_request",
                "Node still syncing blockchain, skipping..."
            );
            handler.send_action(channel, ProtocolGenericAction::Skip).await;
            continue
        }

        debug!(target: "darkfid::proto::protocol_sync::handle_receive_fork_request", "Received request: {request:?}");

        // Retrieve proposals sequence
        let proposals = match validator
            .consensus
            .get_fork_proposals_after(request.tip, request.fork_tip, BATCH as u32)
            .await
        {
            Ok(p) => p,
            Err(e) => {
                debug!(
                    target: "darkfid::proto::protocol_sync::handle_receive_fork_request",
                    "Getting fork proposals failed: {}",
                    e
                );
                handler.send_action(channel, ProtocolGenericAction::Skip).await;
                continue
            }
        };

        // Send response
        handler
            .send_action(channel, ProtocolGenericAction::Response(ForkSyncResponse { proposals }))
            .await;
    }
}

/// Background handler function for ProtocolSyncForkHeaderHash.
async fn handle_receive_fork_header_hash_request(
    handler: ProtocolGenericHandlerPtr<ForkHeaderHashRequest, ForkHeaderHashResponse>,
    validator: ValidatorPtr,
) -> Result<()> {
    debug!(target: "darkfid::proto::protocol_sync::handle_receive_fork_header_hash_request", "START");
    loop {
        // Wait for a new fork header hash request message
        let (channel, request) = match handler.receiver.recv().await {
            Ok(r) => r,
            Err(e) => {
                debug!(
                    target: "darkfid::proto::protocol_sync::handle_receive_fork_header_hash_request",
                    "recv fail: {e}"
                );
                continue
            }
        };

        // Check if node has finished syncing its blockchain
        if !*validator.synced.read().await {
            debug!(
                target: "darkfid::proto::protocol_sync::handle_receive_fork_header_hash_request",
                "Node still syncing blockchain, skipping..."
            );
            handler.send_action(channel, ProtocolGenericAction::Skip).await;
            continue
        }

        debug!(target: "darkfid::proto::protocol_sync::handle_receive_fork_header_hash_request", "Received request: {request:?}");

        // Retrieve fork header
        let fork_header = match validator
            .consensus
            .get_fork_header_hash(request.height, &request.fork_header)
            .await
        {
            Ok(h) => h,
            Err(e) => {
                debug!(
                    target: "darkfid::proto::protocol_sync::handle_receive_fork_header_hash_request",
                    "Getting fork header hash failed: {}",
                    e
                );
                handler.send_action(channel, ProtocolGenericAction::Skip).await;
                continue
            }
        };

        // Send response
        handler
            .send_action(
                channel,
                ProtocolGenericAction::Response(ForkHeaderHashResponse { fork_header }),
            )
            .await;
    }
}

/// Background handler function for ProtocolSyncForkHeaders.
async fn handle_receive_fork_headers_request(
    handler: ProtocolGenericHandlerPtr<ForkHeadersRequest, ForkHeadersResponse>,
    validator: ValidatorPtr,
) -> Result<()> {
    debug!(target: "darkfid::proto::protocol_sync::handle_receive_fork_headers_request", "START");
    loop {
        // Wait for a new fork header hash request message
        let (channel, request) = match handler.receiver.recv().await {
            Ok(r) => r,
            Err(e) => {
                debug!(
                    target: "darkfid::proto::protocol_sync::handle_receive_fork_headers_request",
                    "recv fail: {e}"
                );
                continue
            }
        };

        // Check if node has finished syncing its blockchain
        if !*validator.synced.read().await {
            debug!(
                target: "darkfid::proto::protocol_sync::handle_receive_fork_headers_request",
                "Node still syncing blockchain, skipping..."
            );
            handler.send_action(channel, ProtocolGenericAction::Skip).await;
            continue
        }

        // Check if request exists the configured limit
        if request.headers.len() > BATCH {
            debug!(
                target: "darkfid::proto::protocol_sync::handle_receive_fork_headers_request",
                "Node requested more headers than allowed."
            );
            handler.send_action(channel, ProtocolGenericAction::Skip).await;
            continue
        }

        debug!(target: "darkfid::proto::protocol_sync::handle_receive_fork_headers_request", "Received request: {request:?}");

        // Retrieve fork headers
        let headers = match validator
            .consensus
            .get_fork_headers(&request.headers, &request.fork_header)
            .await
        {
            Ok(h) => h,
            Err(e) => {
                debug!(
                    target: "darkfid::proto::protocol_sync::handle_receive_fork_headers_request",
                    "Getting fork headers failed: {}",
                    e
                );
                handler.send_action(channel, ProtocolGenericAction::Skip).await;
                continue
            }
        };

        // Send response
        handler
            .send_action(channel, ProtocolGenericAction::Response(ForkHeadersResponse { headers }))
            .await;
    }
}

/// Background handler function for ProtocolSyncForkProposals.
async fn handle_receive_fork_proposals_request(
    handler: ProtocolGenericHandlerPtr<ForkProposalsRequest, ForkProposalsResponse>,
    validator: ValidatorPtr,
) -> Result<()> {
    debug!(target: "darkfid::proto::protocol_sync::handle_receive_fork_proposals_request", "START");
    loop {
        // Wait for a new fork header hash request message
        let (channel, request) = match handler.receiver.recv().await {
            Ok(r) => r,
            Err(e) => {
                debug!(
                    target: "darkfid::proto::protocol_sync::handle_receive_fork_proposals_request",
                    "recv fail: {e}"
                );
                continue
            }
        };

        // Check if node has finished syncing its blockchain
        if !*validator.synced.read().await {
            debug!(
                target: "darkfid::proto::protocol_sync::handle_receive_fork_proposals_request",
                "Node still syncing blockchain, skipping..."
            );
            handler.send_action(channel, ProtocolGenericAction::Skip).await;
            continue
        }

        // Check if request exists the configured limit
        if request.headers.len() > BATCH {
            debug!(
                target: "darkfid::proto::protocol_sync::handle_receive_fork_proposals_request",
                "Node requested more proposals than allowed."
            );
            handler.send_action(channel, ProtocolGenericAction::Skip).await;
            continue
        }

        debug!(target: "darkfid::proto::protocol_sync::handle_receive_fork_proposals_request", "Received request: {request:?}");

        // Retrieve fork headers
        let proposals = match validator
            .consensus
            .get_fork_proposals(&request.headers, &request.fork_header)
            .await
        {
            Ok(p) => p,
            Err(e) => {
                debug!(
                    target: "darkfid::proto::protocol_sync::handle_receive_fork_proposals_request",
                    "Getting fork proposals failed: {}",
                    e
                );
                handler.send_action(channel, ProtocolGenericAction::Skip).await;
                continue
            }
        };

        // Send response
        handler
            .send_action(
                channel,
                ProtocolGenericAction::Response(ForkProposalsResponse { proposals }),
            )
            .await;
    }
}